本帖最后由 wwwwwllllk 于 2022-10-20 21:59 编辑
modal中需要填写,所以用了antd-design的modal和form组件。
问题一:如何使用mdal的确定事件提交表单的值
通过使用useRef解决
console.log(form.current.getFieldsValue());
问题二:表单中的显示内容有关联。(选中物品就要显示价格,这里也好实现。但是后端传值的时候物品和价格都要传,)
但是这样写以后传的又是对象,所以总有点小瑕疵,但总比字段不统一拼接传值好很多了。
但是用了modal,form的必填项只是提示,而不是强制限制了。所以我需要加代码来进行限制。
import React, { useState, useRef } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Button, Modal, Form, Input, Select } from "antd";
const { Option } = Select;
const App: React.FC = () => {
const [isModalOpen, setIsModalOpen] = useState(false);
const form = useRef();
const userInfo = { idCard: "340202197104106891", earthday: "1971" };
const showModal = () => {
setIsModalOpen(true);
};
const goods = [
{ name: "笔记本", price: "8000" },
{ name: "铅笔", price: "2" },
{ name: "笔筒", price: "4" }
];
const handleOk = () => {
// setIsModalOpen(false);
// console.log(form.current.submit());
console.log(form.current.getFieldsValue());
};
const handleCancel = () => {
setIsModalOpen(false);
};
const onFinish = (values: any) => {
console.log("Success:", values);
};
const onFinishFailed = (errorInfo: any) => {
console.log("Failed:", errorInfo);
};
const handleChange = (value: string,evt) => {
console.log(evt);
form.current.setFieldsValue({'price': evt.value})
// 可能存在名字一样但是价格不一样的情况
};
return (
<>
<Button type="primary" onClick={showModal}>
填写入职表
</Button>
<Modal
title="入职表"
open={isModalOpen}
onOk={handleOk}
onCancel={handleCancel}
>
<Form
name="basic"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
initialValues={{ remember: true }}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
ref={form}
>
{/* <Form.Item
label="姓名"
name="username"
rules={[{ required: true, message: "请输入姓名" }]}
>
<Input />
</Form.Item> */}
{/* <Form.Item
label="年龄"
name="age"
rules={[{ required: true, message: "请输入年龄" }]}
>
<Input />
</Form.Item> */}
<Form.Item
label="物品"
name="goods"
rules={[{ required: true, message: "身份证号" }]}
>
<Select style={{ width: 120 }} onChange={handleChange} labelInValue>
{goods.map((good,index) => {
return <Option key={index} value={good.price}>{good.name}</Option>;
})}
</Select>
</Form.Item>
<Form.Item
label="价格"
name="price"
rules={[{ required: true, message: "价格" }]}
>
<Input/>
</Form.Item>
</Form>
</Modal>
</>
);
};
export default App;