[英]React Hook Form Controller Issues
I have been using react hook form library with native elements but would like to switch to custom components using the Controller API.我一直在使用带有本机元素的反应钩子表单库,但想使用 Controller API 切换到自定义组件。
I am having an issue with my custom input component updating React state but not updating the ref inside the form state.我的自定义输入组件更新 React state 但没有更新表单 state 中的 ref 时遇到问题。 Thus, a required field is always marked as invalid and I cannot submit my form.
因此,必填字段始终被标记为无效,我无法提交表单。
Here is a demo of my issue: https://codesandbox.io/s/react-hook-form-controller-bofv5这是我的问题的演示: https://codesandbox.io/s/react-hook-form-controller-bofv5
It should log out form data upon submission - but submission never happens because form is not valid.它应该在提交时注销表单数据 - 但提交永远不会发生,因为表单无效。
I think I have narrowed down your issue.我想我已经缩小了你的问题。 First I removed the
rules={{ required: true }}
from the controller and tried the form.首先,我从 controller 中删除了
rules={{ required: true }}
并尝试了表单。 It told me firstName: undefined
.它告诉我
firstName: undefined
。 Then I commented out the onChange
attribute.然后我注释掉了
onChange
属性。 After that, the form is working fine.之后,表格工作正常。 It seems that
onChange
should be used if you want to provide a custom value extractor.如果您想提供自定义值提取器,似乎应该使用
onChange
。 The value needs to be returned from the function.该值需要从 function 返回。 An example of a simple input would be this:
onChange={([{target}]) => target.value}
reference .一个简单输入的示例如下:
onChange={([{target}]) => target.value}
reference 。 Additionally, it is important to note that handleSubmit
extracts some internal state with the values, like that you don't need to keep track of those yourself.此外,需要注意的是,
handleSubmit
提取一些内部 state 的值,就像您不需要自己跟踪这些值一样。
This updated component seems to be working:这个更新的组件似乎正在工作:
function App() {
const { control, handleSubmit, errors } = useForm();
// const [data, setData] = useState({ firstName: "" });
const onSubmit = data => console.log(data);
// const onChangeHandler = e => {
// const { name, value } = e.target;
// const _data = { ...data };
// _data[name] = value;
// setData(_data);
// };
return (
<>
{/* <p>{JSON.stringify(data)}</p> */}
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
as={Input}
name="firstName"
id="firstName"
label="First Name"
control={control}
// value={data.firstName}
rules={{ required: true }}
errors={errors.firstName}
// onChange={([e]) => onChangeHandler(e)}
/>
<input type="submit" />
</form>
</>
);
}
Just a side note, I've never worked with this library so only trust me as far as you can toss me.只是一个旁注,我从来没有使用过这个图书馆,所以只要你能折腾我就相信我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.