我有组件:
const FormComponent = () => {
const { register, handleSubmit, errors } = useForm();
const [val, setVal] = useState("");
const handleSubmitForm = () => console.log("send!");
const handleChange = (e) => {
setVal(e.target.value);
};
return (
<form onSubmit={handleSubmit(handleSubmitForm)}>
<input
type="text"
name="test"
value={val}
ref={register({ required: "The field is required." })}
onChange={handleChange}
/>
{errors.test && errors.test.message}
<button type="submit">Send</button>
</form>
);
};
当我点击“提交”时,react-hook-form
显示错误消息:'该字段是必需的。'。当我想写单词“TEST”然后我尝试删除此文本时,例如选择所有文本并单击 Backspace 按钮,然后我无法从输入中删除此文本,但显示有关空值的消息。
我如何使用
react-hook-form
与 value
和 onChange
事件?Demo codesandbox
最佳答案
不需要有 value 和 onChange。您可以使用不受控制的形式,如果您需要其中一个输入的值,您可以简单地观看它;-)
const FormComponent = () => {
const { register, handleSubmit, watch, errors } = useForm();
const handleSubmitForm = (data) => console.log(data);
const valueOfTest = watch('test');
useEffect(() => {
//consider this to be onchange function
doSomething(valueOfTest);
}, [valueOfTest]);
return (
<form onSubmit={handleSubmit(handleSubmitForm)}>
<input
type="text"
name="test"
ref={register({ required: "The field is required." })}
/>
{errors.test && errors.test.message}
<button type="submit">Send</button>
</form>
);
};
关于reactjs - 提交后,react-hook-form 无法正确验证值和 onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65928525/