作者:夜幕下的狂人_119 | 来源:互联网 | 2023-06-08 12:04
我正在尝试弄清楚如何在Antd前端使用react-hook-form。
我已经制作了此表单,并且看起来没有问题(它是多部分表单向导的第1部分),
有人能看到我在合并这两种表单系统时做错了什么吗?
我没有收到任何错误,但是我想我已经要求同时填写两个表单字段,但是如果我在未完成填写的情况下按提交,则不会显示错误消息。
import React from "react";
import useForm from "react-hook-form";
import { BrowserRouter as Router,Route } from "react-router-dom";
import { StateMachineProvider,createStore } from "little-state-machine";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";
import updateaction from "./updateaction";
import { Button,Form,Input,Divider,Layout,Typography,Skeleton,Switch,Card,Icon,Avatar } from 'antd';
const { Content } = Layout
const { Text,Paragraph } = Typography;
const { Meta } = Card;
createStore({
data: {}
});
const General = props => {
const { register,handleSubmit,errors } = useForm();
const { action } = useStateMachine(updateaction);
const OnSubit= data => {
action(data);
props.history.push("./ProposalMethod");
};
return (
#fff',padding: 24,margin: "auto",minHeight: 280,width: '70%'
}}
>
Part 1: General
name="title"
placeholder="Add a title"
ref={register({ required: true })}
/>
{errors.title && 'A title is required.'}
name="subtitle"
placeholder="Add a subtitle"
ref={register({ required: true })}
/>
{errors.subtitle && 'A subtitle is required.'}
);
};
export default withRouter(General);
这是我的工作方法:
const Example = () => {
const { control,handleSubmit,errors } = useForm()
const OnSubmit= data => console.log(data)
console.log(errors)
return (
name="email"
cOntrol={control}
rules={{ required: "Please enter your email address" }}
as={
label="name"
validateStatus={errors.email && "error"}
help={errors.email && errors.email.message}
>
}
/>
)
}
,
编写此类代码时:
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 (
);
};
# Logs
Input {props: Object,context: Object,refs: Object,updater: Object,saveClearableInput: function ()…}
请注意,antd
是一个完整的UI库(使用第3方“助手”应“转红灯”),尤其是Form
已实现了验证器,您可以看到{{3 }}。
,
此处为反应挂钩形式的作者。 Antd Input组件并没有真正公开内部ref
,因此您必须在register
期间useEffect
,并在onChange期间更新值,例如:
const { register,setValue } = useForm();
useEffect(() => {
register({ name: 'yourField' },{ required: true });
},[])
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 (
console.log(data))}>
as={}
rules={{ required: true }}
name="reactSelect"
register={register}
setValue={setValue}
/>
);
}
,
如果任何人仍然有兴趣接近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 = (
type="email"
placeholder="Email"
OnChange={e => setValue('email',e.target.value,true)}
OnBlur={e => setValue('email',true)}
/>
);
return (
as={EmailInput}
name="email"
cOntrol={control}
defaultValue=""
rules={{
required: true
}}
validateStatus={emailError ? 'error' : ''}
help={emailError}
/>
);
}
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 (
validateStatus={errors && errors['email'] ? 'error' : ''}
help={errors.email?.message}
>
as={Input}
name="email"
autoComplete="email"
cOntrol={control}
placeholder={intl.formatMessage({ id: 'AUTH_INPUT_EMAIL' })}
/>
validateStatus={errors && errors['password'] ? 'error' : ''}
help={errors.password?.message}
>
as={Input}
name="password"
type="password"
cOntrol={control}
autoComplete="new-password"
defaultValue=""
placeholder={intl.formatMessage({ id: 'AUTH_INPUT_PASSWORD' })}
/>
);
}
export default SignInForm;