我正在嘗試創建 2 個密碼欄位并想檢查 2 個密碼是否相同,如果它們相同,則應啟用注冊按鈕。
const [passwordOne, setPasswordOne] = useState("");
const [passwordTwo, setPasswordTwo] = useState("");
const [disabled, setDisabled] = useState(true);
function checkPassword(input1, input2) {
if (input1 === input2) {
setDisabled(false);
setOutput("");
} else {
setDisabled(true);
setOutput("Passwords do not match");
}
}
<input
onChange={(e) => {
setPasswordOne(e.target.value);
checkPassword(passwordOne, passwordTwo)}}
/>
<input
onChange={(e) => {
setPasswordTwo(e.target.value);
checkPassword(passwordOne, passwordTwo)}}
/>
<button disabled={disabled}>Register</button>
uj5u.com熱心網友回復:
您沒有在支票中使用最新密碼的值。
呼叫應該是:
checkPassword(e.target.value, passwordTwo)
// and
checkPassword(passwordOne, e.target.value)
考慮簡化狀態:
const [passwordOne, setPasswordOne] = useState("");
const [passwordTwo, setPasswordTwo] = useState("");
const isPasswordFilled = passwordOne !== "";
const arePasswordsSame = isPasswordFilled && passwordOne === passwordTwo;
return <>
<input onChange={(e) => setPasswordOne(e.target.value) />
<input onChange={(e) => setPasswordTwo(e.target.value) />
{isPasswordFilled === true && arePasswordsSame === false && <p>Passwords do not match</p>}
<button disabled={isPasswordFilled === false || arePasswordsSame
=== false}>Register</button>
</>;
uj5u.com熱心網友回復:
const [passwordOne, setPasswordOne] = useState("");
const [passwordTwo, setPasswordTwo] = useState("");
const [disabled, setDisabled] = useState(true);
const [output, setOutput] = useState("");
function checkPassword(input1, input2) {
if (input1 === input2) {
setDisabled(false);
setOutput("");
} else {
setDisabled(true);
setOutput("Passwords do not match");
}
}
<input
onChange={(e) => {
setPasswordOne(e.target.value);
checkPassword(e.target.value, passwordTwo)}}
/>
<input
onChange={(e) => {
setPasswordTwo(e.target.value);
checkPassword(passwordOne, e.target.value)}}
/>
<p>{output}</p>
<button disabled={disabled}>Register</button>
您正在發送尚未設定的狀態值。因此,如果您可以發送當前引數,則效果很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/503790.html
標籤:javascript 反应 反应钩子
