文档地址: 链接.
import React, { useState, useEffect } from "react";
import { Form, Input, Button, Checkbox } from "antd";
function App() {
const [form] = Form.useForm();
const [checkNick, setCheckNick] = useState(false);
useEffect(() => {
form.validateFields(["nickname"]);
}, [checkNick]);
async function onCheck() {
try {
const values = await form.validateFields();
console.log("Success:", values);
} catch (errorInfo) {
console.log("Failed:", errorInfo);
}
}
return (
<Form
form={form}
name="dynamic_rule"
initialValues={{
checkboxBool: false,
}}
>
<Form.Item
label="姓名"
name="username"
rules={[
{
required: true,
message: "名字为必填项.",
},
]}
>
<Input placeholder="请输入你的名字" />
</Form.Item>
<Form.Item
label="昵称"
name="nickname"
rules={[
{
required: checkNick,
message: "昵称为必填项.",
},
]}
>
<Input placeholder="请输入昵称" />
</Form.Item>
<Form.Item name="checkboxBool" valuePropName="checked">
<Checkbox
onChange={(e) => {
setCheckNick(e.target.checked);
}}
>
昵称为必填项
</Checkbox>
</Form.Item>
<Form.Item>
<Button onClick={onCheck}>检查</Button>
</Form.Item>
</Form>
);
}
export default App;
|