Ris*_*nha 11 reactjs next.js antd react-hook-form
我正在尝试将 antd 形式与react-hook-form 一起使用,但无法使其工作。
基本上我正在使用 antd 的主题,并希望集成react-hook-form以获得更好的验证和其他功能。到目前为止这是代码
import { Button, Form, Input, Message, Row, Tooltip } from "antd";
import { useForm, Controller } from "react-hook-form";
import {
EyeTwoTone,
MailTwoTone,
PlaySquareTwoTone,
QuestionCircleTwoTone,
SkinTwoTone,
} from "@ant-design/icons";
import Link from "next/link";
import Router from "next/router";
import styled from "styled-components";
const FormItem = Form.Item;
const Content = styled.div`
max-width: 400px;
z-index: 2;
min-width: 300px;
`;
const Register = (props) => {
const defaultValues = {
name: null,
phone: null,
email: null,
password: null,
confirmPassword: null,
checked: false,
};
const { handleSubmit, reset, watch, control, errors, getValues } = useForm({
defaultValues,
});
// const { register, errors, handleSubmit, control } = useForm({
// mode: 'onChange',
// });
const onSubmit = async (data) => {
try {
console.log("data", data);
} catch (err) {
console.log("err", err);
}
};
return (
<Row
type="flex"
align="middle"
justify="center"
className="px-3 bg-white"
style={{ minHeight: "100vh" }}
>
<Content>
<div className="text-center mb-5">
<Link href="/signup">
<a className="brand mr-0">
<PlaySquareTwoTone style={{ fontSize: "32px" }} />
</a>
</Link>
<h5 className="mb-0 mt-3">Sign up</h5>
<p className="text-muted">create a new account</p>
</div>
<Form layout="vertical" onSubmit={handleSubmit(onSubmit)}>
<Controller
as={
<FormItem
label="Email"
name="email"
rules={[
{
type: "email",
message: "The input is not valid E-mail!",
},
{
required: true,
message: "Please input your E-mail!",
},
]}
>
<Input
prefix={<MailTwoTone style={{ fontSize: "16px" }} />}
type="email"
placeholder="Email"
/>
</FormItem>
}
control={control}
name="select"
/>
{/* <Input inputRef={register} name="input" /> */}
<button type="button" onClick={() => reset({ defaultValues })}>
Reset
</button>
<input type="submit" />
</Form>
</Content>
</Row>
);
};
export default Register;
Run Code Online (Sandbox Code Playgroud)
现在,正如您所看到的,我有常规表单标签,其中有输入字段。但是使用常规表单,我没有获得 antd 表单提供的布局道具。我也无法在提交期间获取值。
所以我的问题是,如何将 AntD 表单组件与 React hook 表单一起使用,以便我可以利用 React-hook0form 以及 Antd 样式的优点。
gaz*_*rgo 11
只需使用ant design内置的useForm方法即可,无需拉入第三方。看起来像:
const [form] = Form.useForm();
Run Code Online (Sandbox Code Playgroud)
Form 也有ant 中onFinish没有的方法onSubmit,至少在版本 4 中是这样。
使用controllerreact-hook-form中的包装器,文档链接
进口控制器
import { useForm, Controller } from 'react-hook-form';
Run Code Online (Sandbox Code Playgroud)
来电control来自useForm
const { handleSubmit, control } = useForm();
Run Code Online (Sandbox Code Playgroud)
您的意见
<Form.Item label="Email">
<Controller
name="email"
defaultValue=""
control={control}
render={({ onChange, value }) => (
<Input onChange={onChange} value={value} />
)}/>
</Form.Item>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37538 次 |
| 最近记录: |