如何在 ant design 或 material UI 中使用 react-hook-form
How to use react-hook-form with ant design or material UI
我正在尝试使用 react-hook-form 库来验证表单。当我使用 ant design 或 material UI 渲染视图时,它无法正常工作。
<Input name="firstName" ref={register({ required: true })} />
{errors.firstName && 'First name is required'}
发生了一些警告:"Missing name at....."
。
对于 Material-UI,您可以通过 TextField 组件道具 register
传递 inputRef
(我也在使用 Yup 进行验证模式)
import React, { useState } from 'react';
import { Button, TextField } from '@material-ui/core';
import useForm from 'react-hook-form';
import { object, string } from 'yup';
const Form: React.FC = () => {
const schema = object().shape({
username: string().required('Username is required'),
password: string().required('Password is required'),
});
const { register, handleSubmit, errors } = useForm({ validationSchema: schema });
const onSubmit = (data: any) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="username"
error={!!errors.username}
label="Username"
helperText={errors.username ? errors.username.message : ''}
type="email"
inputRef={register}
fullWidth
/>
<TextField
name="password"
error={!!errors.password}
label="Password"
inputRef={register}
helperText={errors.password ? errors.password.message : ''}
type="password"
fullWidth
/>
<Button
color="primary"
type="submit"
variant="contained"
fullWidth
>
Submit
</Button>
</form>
);
};
这里是作者的反应钩子。 React Hook Form 拥抱非受控组件和原生输入,但是很难避免使用外部受控组件,例如 React-Select、AntD 和 Material-UI。所以我构建了一个包装器组件来帮助您更轻松地集成。
https://github.com/react-hook-form/react-hook-form-input
好吧,你可能想知道这样做有什么意义,你从带有受控组件的 React Hook 表单中得到了什么?首先,您仍然可以根据自己的选择从我们的内部构建验证或模式验证中受益。其次,这将通过将您的输入状态更新隔离到自身来提高您的应用程序或表单性能,这意味着即使使用受控组件,您的表单根也可以通过 0 次重新渲染得到结果。
这是codesandbox的例子:
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。
V4 的最新建议是使用内置的 <Controller />
组件 (docs)。您不需要安装 react-hook-form-input
.
的额外依赖项
来自react-hook-form-input的README.md:
This component is now a part of React Hook Form V4, and renamed to Controller with much simpler API.
示例:
<Controller
as={<TextField />}
name="firstName"
control={control}
defaultValue=""
/>
请注意,已接受答案的作者@Bill 现在也 says 认为答案已过时 "please use controller instead."
对 TextField 组件使用 inputRef 应该足够了,对于任何默认值,react-hook-form (useForm) 提供 defaultValue 以防您想使用一些默认值或 material-ui 在他们的 TextField 中有默认值 API
const { register, handleSubmit, errors, watch } = useForm({ mode: 'onChange' });
<TextField
inputRef={register({ required: true })}
label="Email Address"
name="email"
type="email"
autoComplete="email"
onChange={handleUpdate}
error={errors.email}
helperText={errors.email && 'email required'}
/>
我使用其他人提到的 TextField inputRef
方法遇到了 0 个问题。
<TextField
inputRef={register}
id="name"
name="name"
/>
我在这里发布了一个完整的工作版本:https://seanconnolly.dev/react-hook-form-material-ui
我正在尝试使用 react-hook-form 库来验证表单。当我使用 ant design 或 material UI 渲染视图时,它无法正常工作。
<Input name="firstName" ref={register({ required: true })} />
{errors.firstName && 'First name is required'}
发生了一些警告:"Missing name at....."
。
对于 Material-UI,您可以通过 TextField 组件道具 register
传递 inputRef
(我也在使用 Yup 进行验证模式)
import React, { useState } from 'react';
import { Button, TextField } from '@material-ui/core';
import useForm from 'react-hook-form';
import { object, string } from 'yup';
const Form: React.FC = () => {
const schema = object().shape({
username: string().required('Username is required'),
password: string().required('Password is required'),
});
const { register, handleSubmit, errors } = useForm({ validationSchema: schema });
const onSubmit = (data: any) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="username"
error={!!errors.username}
label="Username"
helperText={errors.username ? errors.username.message : ''}
type="email"
inputRef={register}
fullWidth
/>
<TextField
name="password"
error={!!errors.password}
label="Password"
inputRef={register}
helperText={errors.password ? errors.password.message : ''}
type="password"
fullWidth
/>
<Button
color="primary"
type="submit"
variant="contained"
fullWidth
>
Submit
</Button>
</form>
);
};
这里是作者的反应钩子。 React Hook Form 拥抱非受控组件和原生输入,但是很难避免使用外部受控组件,例如 React-Select、AntD 和 Material-UI。所以我构建了一个包装器组件来帮助您更轻松地集成。
https://github.com/react-hook-form/react-hook-form-input
好吧,你可能想知道这样做有什么意义,你从带有受控组件的 React Hook 表单中得到了什么?首先,您仍然可以根据自己的选择从我们的内部构建验证或模式验证中受益。其次,这将通过将您的输入状态更新隔离到自身来提高您的应用程序或表单性能,这意味着即使使用受控组件,您的表单根也可以通过 0 次重新渲染得到结果。
这是codesandbox的例子: 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。
V4 的最新建议是使用内置的 <Controller />
组件 (docs)。您不需要安装 react-hook-form-input
.
来自react-hook-form-input的README.md:
This component is now a part of React Hook Form V4, and renamed to Controller with much simpler API.
示例:
<Controller
as={<TextField />}
name="firstName"
control={control}
defaultValue=""
/>
请注意,已接受答案的作者@Bill 现在也 says 认为答案已过时 "please use controller instead."
对 TextField 组件使用 inputRef 应该足够了,对于任何默认值,react-hook-form (useForm) 提供 defaultValue 以防您想使用一些默认值或 material-ui 在他们的 TextField 中有默认值 API
const { register, handleSubmit, errors, watch } = useForm({ mode: 'onChange' });
<TextField
inputRef={register({ required: true })}
label="Email Address"
name="email"
type="email"
autoComplete="email"
onChange={handleUpdate}
error={errors.email}
helperText={errors.email && 'email required'}
/>
我使用其他人提到的 TextField inputRef
方法遇到了 0 个问题。
<TextField
inputRef={register}
id="name"
name="name"
/>
我在这里发布了一个完整的工作版本:https://seanconnolly.dev/react-hook-form-material-ui