在 ReactJs 中导入作为功能组件归档的密码

Import password filed as an functional component in ReactJs

我想将这个反应钩子和密码字段存储在一个单独的 js 文件中,我想将它导入到我的注册表单中,我该怎么做?

密码字段

  <label class="font-medium block mb-1 mt-6 text-gray-700" for="password">
    Password
  </label>
  <div class="relative w-full">
    <div class="absolute inset-y-0 right-0 flex items-center px-2">
      <input class="hidden js-password-toggle" id="toggle" type="checkbox" />
      <label class="bg-gray-300 hover:bg-gray-400 rounded px-2 py-1 text-sm text-gray-600 font-mono cursor-pointer js-password-label" for="toggle">show</label>
    </div>
    <input class="appearance-none border-2 rounded w-full py-3 px-3 leading-tight border-gray-300 bg-gray-100 focus:outline-none focus:border-indigo-700 focus:bg-white text-gray-700 pr-16 font-mono js-password" id="password" type="password" autocomplete="off"
    />
  </div>

密码函数归档

useEffect(() => {

  const passwordToggle = document.querySelector('.js-password-toggle')

  passwordToggle.addEventListener('change', function() {
    const password = document.querySelector('.js-password'),
      passwordLabel = document.querySelector('.js-password-label')

    if (password.type === 'password') {
      password.type = 'text'
      passwordLabel.innerHTML = 'hide'
    } else {
      password.type = 'password'
      passwordLabel.innerHTML = 'show'
    }

    password.focus()
  })

}, [])

我要添加此密码的表单

import React, { useEffect, useState } from "react";
import Buttons from "../../../elements/form/Button";
import PasswordInput from "../../../elements/form/PasswordInput";
import { Col, Input, Row, Select, Form, InputNumber, Divider } from "antd";
import { ChangePassword, sentOtp, changePhoneNumber, requestOtp } from "./SecurityApi";

const { Option } = Select;



const Security = () => {



  const [phoneNo, setPhoneNo] = useState("");
  const [otp, setOtp] = useState("");
  //const [password, setPassword] = useState("");
  const [conPassword, setConPassword] = useState("");
  const [passError, setPassError] = useState();
  const [otpError, setOtpError] = useState();
  const [user, setUser] = useState(null);


  //changing password
    const [editPasswordState, setEditPasswordState] = useState(false);
    const [password, setPassword] = useState({
      password: "",
    });
    
    const handlePasswordChange = async () => {
      if (password === user.password) {
        return;
      }
      if (password.trim() === "") {
        console.log("cant be empty");
    
        return;
      }
    
      await ChangePassword(password, setUser);
    };

  useEffect(() => {
    setPassError(password && conPassword && password !== conPassword);
  }, [password, conPassword]);

  useEffect(() => {
    setOtpError(!otp && phoneNo);
  }, [otp]);
//onSubmit password
  const onSubmit = async () => {
    if (passError) return false;
    try {
      const res = await ChangePassword({ password });
      setPassword("");
      setConPassword("");
      alert("Password Changed !!");
    } catch (error) {
      alert("Something went wrong !!");
    }
  };
//OTP
  const sendOtp = async () => {
    if (phoneNo === "") return false;
    try {
      const res = await sentOtp(phoneNo);
      alert(`Otp is ${res} !!`);
    } catch (error) {
      alert("Something went wrong !!");
    }
  };
//Changing the phone number
  const changePhoneNo = async () => {
    if (phoneNumber === "") return false;
    if (otp === "") {
      setOtpError(true);
      return false;
    }
    try {
      const res = await changePhoneNumber(phoneNo);
      setPhoneNumber("");
      setOtp("");
      alert("Phone Number Changed !!");
    } catch (error) {
      alert("Something went wrong !!");
    }
  };

  const [editPhoneNumberState, setEditPhoneNumberState] = useState(false);
  const [phoneNumber, setPhoneNumber] = useState({
    password: "",
  });
  
  const handlePhoneNumberChange = async () => {
    if (phoneNumber === user.phoneNumber) {
      return;
    }
    if (password.trim() === "") {
      console.log("cant be empty");
  
      return;
    }
  
    await ChangePassword(password, setUser);
  };
   
  return (
    <>
      <div className="md:pl-8 sm:pl-0 ">
        {/*  ----------    Password Change  ------------  */}
        <div class="mt-10 sm:mt-0">
          <div class="md:grid md:grid-cols-3 md:gap-6">
            <div class="md:col-span-1">
              <div class="px-4 sm:px-0">
                <h3 class="text-lg font-medium leading-6 text-gray-900">
                  Change Password
                </h3>
                <p class="mt-1 text-sm text-gray-600">Change password here</p>
              </div>
            </div>
            <div class="mt-5 md:mt-0 md:col-span-2">
              <form action="#" method="POST">
                <div class="shadow overflow-hidden sm:rounded-md">
                  <div class="px-4 py-3 bg-gray-50 text-right sm:px-6">
                  <div class="grid grid-cols-6 gap-6">
                    <div class="col-span-6 sm:col-span-3">
                    <Buttons
                      title={
                        !editPasswordState ? "Edit Full Password" : "Cancel"
                        }
                      outline
                      onClick={() => {
                        setEditPasswordState(!editPasswordState);
                      }}
                      class="inline-flex 
                            justify-center 
                            py-2 px-4 border 
                            border-transparent 
                            shadow-sm text-sm 
                            font-medium rounded-md 
                            text-white bg-red-400 
                            hover:bg-red-400 
                            focus:outline-none f
                            ocus:ring-2 
                            focus:ring-offset-2 
                            focus:ring-red-500"
                    />
                  </div>
                  <div class="col-span-6 sm:col-span-3">
                            {editPasswordState && (
                              <Buttons
                                title="Save"
                                onClick={async () => {
                                  setEditPasswordState(false);
                                  await handlePasswordChange();
                                }}
                              />
                            )}
                   </div>       
                   </div>  
                   </div>   
                  <div class="px-4 py-5 bg-white sm:p-6">
{/* OTP Check*/}
<div class="grid grid-cols-6 gap-1">
                      <div class="col-span-4 sm:col-span-3">
                        <label
                          for="first-name"
                          class="block text-sm font-medium text-gray-700"
                        >
                          Send OTP
                        </label>

                        <Buttons
                          title={"Request OTP"}
                          outline
                          onClick={async () => {
                            await requestOtp(user.phoneNumber);
                            }}
                        />

                      </div>
                      <div class="col-span-6 sm:col-span-3">
                        <label
                          for="last-name"
                          class="block text-sm font-medium text-gray-700"
                        >
                          Enter OTP
                        </label>

                        <input
                          type="text"
                          name="last-name"
                          id="last-name"
                          autocomplete="family-name"
                          class="mt-1 
                                      focus:ring-red-400 
                                      focus:border-red-400 
                                      block w-full 
                                      shadow-sm sm:text-sm 
                                      border-gray-300 rounded-md"
                        />
                        {passError && (
                          <Col className="text-red-500">
                            OTP doesn't Correct !!
                          </Col>
                        )}
                      </div>
                    </div>
{/* OTP Check End */}
                  </div>
                  <div class="px-4 py-5 bg-white sm:p-6">
{/* Password Check*/}

                    <div class="grid grid-cols-6 gap-6">
                      <div class="col-span-6 sm:col-span-3">
                        <label
                          for="first-name"
                          class="block text-sm font-medium text-gray-700"
                        >
                          New Password
                        </label>

                        <Input.Password
                          value={password}
                          onChange={(event) => {
                            setPassword(event.target.value);
                          }}
                          class="mt-1 
                          focus:ring-red-400 
                          focus:border-red-400 
                          block w-full 
                          shadow-sm sm:text-sm 
                          border-gray-300 rounded-md"/>

这是地方

                      </div>
                      <div class="col-span-6 sm:col-span-3">
                        <label
                          for="last-name"
                          class="block text-sm font-medium text-gray-700"
                        >
                          Confirm New Password
                        </label>

                        <Input.Password
                          value={conPassword}
                          onChange={(event) => {
                            setConPassword(event.target.value);
                          }}
                        />
                        {passError && (
                          <Col className="text-red-500">
                            Password doesn't match !!
                          </Col>
                        )}
                      </div>
                    </div>
{/* Password Check End*/}
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>

        {/*    ------- End Password Change   --------   */}
        <div class="px-4 py-1 bg-black-50 text-right sm:px-6">
          <Divider></Divider>
        </div>
        {/*     ------------   Mobile Number Change  ----------------    */}

        <div class="mt-10 sm:mt-0">
          <div class="md:grid md:grid-cols-3 md:gap-6">
            <div class="md:col-span-1">
              <div class="px-4 sm:px-0">
                <h3 class="text-lg font-medium leading-6 text-gray-900">
                  Change Mobile Number
                </h3>
                <p class="mt-1 text-sm text-gray-600">
                  Use a permanent address where you can receive mail.
                </p>
              </div>
            </div>
            <div class="mt-5 md:mt-0 md:col-span-2">
              <form action="#" method="POST">
                <div class="shadow overflow-hidden sm:rounded-md">
                  <div class="px-4 py-3 bg-gray-50 text-right sm:px-6">
                  <div class="grid grid-cols-6 gap-6">
                      <div class="col-span-6 sm:col-span-3">
                    <Buttons
                      title={
                        !editPhoneNumberState ? "Edit Phone Number" : "Cancel"
                        }
                      outline
                      onClick={() => {
                        setEditPhoneNumberState(!editPhoneNumberState);
                      }}
                      className={" flex items-center justify-center "}
                    />
                          </div>
                          <div class="col-span-6 sm:col-span-3">
                          {editPhoneNumberState && (
                              <Buttons
                                title="Save"
                                onClick={async () => {
                                  setEditPhoneNumberState(false);
                                  await handlePhoneNumberChange();
                                }}
                              />
                            )}
                          </div>
                          </div>
                        </div>
                  <div/>
                  <div class="px-4 py-5 bg-white sm:p-6">
                    {/** Email Verification */}
                    <div class="grid grid-cols-6 gap-6">
                      <div class="col-span-6 sm:col-span-3">
                        <label
                          for="first-name"
                          class="block text-sm font-medium text-gray-700"
                        >
                          Email
                        </label>
                        <Buttons
                          title="Send Email"
                          onClick={sendOtp}
                          outline
                          class="   inline-flex 
                                justify-center 
                                py-2 px-4 border 
                                border-transparent 
                                shadow-sm text-sm 
                                font-medium rounded-md 
                                text-white bg-red-400 
                                hover:bg-red-400 
                                focus:outline-none f
                                ocus:ring-2 
                                focus:ring-offset-2 
                                focus:ring-red-500"
                        />
                      </div>

                      <div class="col-span-6 sm:col-span-3">
                        <label
                          for="last-name"
                          class="block text-sm font-medium text-gray-700"
                        >
                          Verification Code
                        </label>
                        <input
                          type="text"
                          name="last-name"
                          id="last-name"
                          autocomplete="family-name"
                          class="mt-1 
                                      focus:ring-red-400 
                                      focus:border-red-400 
                                      block w-full 
                                      shadow-sm sm:text-sm 
                                      border-gray-300 rounded-md"
                        />
                      </div>
                    </div>
                    {/** End Email Verification */}
                    {/** Phone Number change */}
                      <div class="grid grid-cols-6 gap-6">
                      <div class="col-span-6 sm:col-span-3">
                        <label
                          for="first-name"
                          class="block text-sm font-medium text-gray-700"
                        >
                          New Mobile Number
                        </label>
                        <input
                          type="text"
                          name="first-name"
                          id="first-name"
                          autocomplete="given-name"
                          class="mt-1 
                                      focus:ring-red-400 
                                      focus:border-red-400 
                                      block w-full 
                                      shadow-sm sm:text-sm 
                                      border-gray-300 rounded-md"
                        />
                      </div>
                    </div>
                    {/** End Email change */}
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
        {/*     ------------   Mobile Number Change  ----------------    */}
      </div>
    </>
  );
};

export default Security;

上面提到的两个部分之间,应该添加密码字段

好的,假设这是您的表单:

import PasswordField from "/PasswordField"

const Form = () => {
  const [password, setPassword] = useState("")
  const [name, setName] = useState("")
  const [lastName, setLastName] = useState("")
  const submitForm = () => {
    //your logic for submitting form
  }
  return (
    <form onSubmit={submitForm}>
      <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} />
      <PasswordField password={password} setPassword={setPassword} />
    </form>
  );
};

export default Form;

请注意,我们正在导入要在表单内部使用的 PasswordField 组件,并将值和用于更改该值的函数作为 props 传递给 PasswordField 组件。

现在让我们创建密码组件:

import React, {useState} from 'react';

const PasswordField = (props) => {
   return (
    <div>
      <label class="font-medium block mb-1 mt-6 text-gray-700" for="password">
        Password
      </label>
      <input id={"password"} type="password" value={props.password} onChange={(e) => props.setPassword(e.target.value)} />
    </div>
  );
};

export default PasswordField;

显然,您需要相应地添加 类 和样式,但我认为这可以帮助您前进。