这是我的工作方法:
const Example = () => {
const { control,handleSubmit,errors } = useForm()
const onSubmit = data => console.log(data)
console.log(errors)
return (
<Form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="email"
control={control}
rules={{ required: "Please enter your email address" }}
as={
<Form.Item
label="name"
validateStatus={errors.email && "error"}
help={errors.email && errors.email.message}
>
<Input />
</Form.Item>
}
/>
<Button htmlType="submit">Submit</Button>
</Form>
)
}
,
编写此类代码时:
<Input
name="subtitle"
placeholder="Add a subtitle"
ref={register({ required: true })}
/>
您假设Input
引用绑定到input
,但这不是真的。
实际上,您需要将其绑定到inputRef.input
。
您可以使用以下代码进行检查:
const App = () => {
const inputRef = useRef();
const inputRefHtml = useRef();
useEffect(() => {
console.log(inputRef.current);
console.log(inputRefHtml.current);
});
return (
<FlexBox>
<Input ref={inputRef} />
<input ref={inputRefHtml} />
</FlexBox>
);
};
# Logs
Input {props: Object,context: Object,refs: Object,updater: Object,saveClearableInput: function ()…}
<input></input>
请注意,antd
是一个完整的UI库(使用第3方“助手”应“转红灯”),尤其是Form
已实现了验证器,您可以看到{{3 }}。
,
此处为反应挂钩形式的作者。 Antd Input组件并没有真正公开内部ref
,因此您必须在register
期间useEffect
,并在onChange期间更新值,例如:
const { register,setValue } = useForm();
useEffect(() => {
register({ name: 'yourField' },{ required: true });
},[])
<Input name="yourField" onChange={(e) => setValue('yourField',e.target.value)}
我已经构建了一个包装器组件,以使antd组件集成更加容易:https://github.com/react-hook-form/react-hook-form-input
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>
);
}
,
如果任何人仍然有兴趣接近Ant提供的Form Inputs的默认样式,这就是我的工作方式:
import { Form,Button,Input } from 'antd';
import { useForm,Controller } from 'react-hook-form';
function MyForm() {
const { control,errors,setValue } = useForm();
const emailError = errors.email && 'Enter your email address';
const onSubmit = data => { console.log(data) };
const EmailInput = (
<Form.Item>
<Input
type="email"
placeholder="Email"
onChange={e => setValue('email',e.target.value,true)}
onBlur={e => setValue('email',true)}
/>
</Form.Item>
);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
as={EmailInput}
name="email"
control={control}
defaultValue=""
rules={{
required: true
}}
validateStatus={emailError ? 'error' : ''}
help={emailError}
/>
<Button block type="primary" htmlType="submit">
Submit
</Button>
</form>
);
}
Codesandbox sample
,
在 Ant Design v4.x + react-hook-form v6.x 中。我们可以正常实现
import { useForm,Controller,SubmitHandler } from 'react-hook-form';
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { useIntl } from 'react-intl';
import { Input,Form } from 'antd';
const SignInSchema = yup.object().shape({
email: yup.string().email().required(),password: yup.string().required('required').min(6,'passwordMin'),});
interface PropTypes {
defaultValues?: {
email: string;
password: string;
};
handleFormSubmit: SubmitHandler<{ email: string; password: string }>;
}
function SignInForm({ defaultValues,handleFormSubmit }: PropTypes) {
const intl = useIntl();
const { handleSubmit,control,errors } = useForm({
defaultValues,resolver: yupResolver(SignInSchema),});
return (
<Form onFinish={handleSubmit(handleFormSubmit)}>
<Form.Item
validateStatus={errors && errors['email'] ? 'error' : ''}
help={errors.email?.message}
>
<Controller
as={Input}
name="email"
autoComplete="email"
control={control}
placeholder={intl.formatMessage({ id: 'AUTH_INPUT_EMAIL' })}
/>
</Form.Item>
<Form.Item
validateStatus={errors && errors['password'] ? 'error' : ''}
help={errors.password?.message}
>
<Controller
as={Input}
name="password"
type="password"
control={control}
autoComplete="new-password"
defaultValue=""
placeholder={intl.formatMessage({ id: 'AUTH_INPUT_PASSWORD' })}
/>
</Form.Item>
<Button type="primary" htmlType="submit">
{intl.formatMessage({ id: 'SIGN_IN_SUBMIT_BUTTON' })}
</Button>
</Form>
);
}
export default SignInForm;
本文链接:https://www.f2er.com/3162676.html