新增
import { Form, Input, InputNumber, Modal, Radio, message } from "antd";
import { useForm } from "antd/es/form/Form";
import { Student } from "../model/Student";
import { useEffect } from "react";
import axios from "axios";
import R from "../model/R";
import { Rule } from "antd/es/form";
export default function A6Insert({
open,
onSuccess,
student,
onCancel,
}: {
open: boolean;
onSuccess?: () => void;
student: Student;
onCancel: () => void;
}) {
const { Item } = Form;
const { Group } = Radio;
const options = [
{ label: "男", value: "男" },
{ label: "女", value: "女" },
];
//form代表表单对象
const [form] = useForm();
async function onOK() {
const values = await form.validateFields();
console.log(values);
const resp = await axios.post<R<string>>(
`http://localhost:8080/api/students`,
values
);
message.success(resp.data.data);
onSuccess && onSuccess();
//新增成功之后,再次点击新增按钮,表单会显示上一次新增的数据,重置表单之后,数据就会回到初始化值
form.resetFields();
}
const nameRules: Rule[] = [
{ required: true, message: "姓名必须" },
{ min: 2, type: "string", message: "至少两个字符" },
];
const ageRules: Rule[] = [
{ required: true, message: "年龄必须" },
{ min: 10, type: "number", message: "至少10岁" },
{ max: 120, type: "number", message: "最大120岁" },
];
return (
<Modal
open={open}
title="新增学生"
onOk={onOK}
onCancel={onCancel}
forceRender
>
<Form form={form} initialValues={student}>
<Item label="姓名" name="name" rules={nameRules}>
<Input></Input>
</Item>
<Item label="性别" name="sex">
<Group
options={options}
optionType="button"
buttonStyle="solid"
></Group>
</Item>
<Item label="年龄" name="age" rules={ageRules}>
<InputNumber></InputNumber>
</Item>
</Form>
</Modal>
);
}
-
initialValues 只会触发一次表单赋初值
-
form.resetFields() 会将表单重置为 initialValues 时的状态