在这里反应钩子表单作者。 React Hook Form 包含不受控制的组件和原生输入,但很难避免使用外部受控组件,例如 React-Select、AntD 和 Material-UI。所以我构建了一个包装器组件来帮助您更轻松地集成。
https://github.com/react-hook-form/react-hook-form-input
好的,您可能想知道这样做有什么意义,以及您从带有受控组件的反应钩子形式中得到什么?首先,您仍然可以从我们选择的构建验证或模式验证中受益。其次,这将通过将您的输入状态更新隔离到自身来提高您的应用程序或表单的性能,这意味着即使使用受控组件,您的表单根也可以重新渲染为 0。
这是代码框示例:
https://codesandbox.io/s/react-hook-form-hookforminput-rzu9s
希望这些是有意义的,并且我创建的额外组件也可以帮助您。
除此之外,我还构建了一个包装器组件以使事情变得更容易:
import React from 'react';
import useForm from 'react-hook-form';
import { RHFInput } from 'react-hook-form-input';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
function App() {
const { handleSubmit, register, setValue, reset } = useForm();
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<RHFInput
as={<Select options={options} />}
rules={{ required: true }}
name="reactSelect"
register={register}
setValue={setValue}
/>
<button
type="button"
onClick={() => {
reset({
reactSelect: '',
});
}}
>
Reset Form
</button>
<button>submit</button>
</form>
);
}
https://github.com/react-hook-form/react-hook-form-input
更新
React-hook-form v4,react-hook-form-input 已合并到主仓库并重命名为 Controller。
https://react-hook-form.com/api#Controller