【发布时间】:2019-10-03 16:31:05
【问题描述】:
我正在使用 React 中的表单,第一次使用函数组件。要么我快疯了,要么这应该没有问题......
import React, {useEffect, useState} from 'react';
function ChangePasswordComponent(props) {
const {onChangePassword} = props;
const [isValid, setIsValid] = useState(true);
const [form, setForm] = useState({
password: undefined,
confirm: undefined
})
useEffect(() => {
handleValidation();
}, [form])
function handleValidation() {
setIsValid(form.password === form.confirm);
}
function onFormValueChanges(event) {
setForm({...form, [event.target.name]: event.target.value})
}
function resetFields() {
setForm({
password: undefined,
confirm: undefined
})
}
function onUpdateClick() {
onChangePassword(form.password);
resetFields();
}
return (
<div className="change-password-container">
<input
type="text"
name="password"
value={form.password}
onChange={(event) => onFormValueChanges(event)}
placeholder="new password" />
<input
type="text"
name="confirm"
value={form.confirm}
onChange={(event) => onFormValueChanges(event)}
placeholder="confirm new password" />
{!isValid ?
<span className="validation-error">passwords do not match</span> : null }
<div className="button-container">
<button onClick={() => resetFields()}>Cancel</button>
<button onClick={() => onUpdateClick()}
disabled={!form.password || !isValid}>Update</button>
</div>
</div>
);
}
export default ChangePasswordComponent;
但是,当我运行代码时,我在控制台中收到关于...的错误。
组件正在更改要控制的文本类型的不受控制的输入。输入元素不应从不受控切换到受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。
当我回顾文档时,我的模式似乎很好地遵循了文档。想法?
【问题讨论】:
-
你应该使用 empty string 比如
''而不是undefined。 -
另外,这不是问题的一部分,但想指出您的代码中有 useEffect 两次调用相同的函数。
-
感谢@DragonWhite。
标签: javascript reactjs