在Antd中,可以使用Form
组件来处理表单的默认值和字段值。下面是一个示例代码,演示了如何在打开模态框时为级联选择器设置默认值或设置字段值:
import React, { useState } from 'react';
import { Modal, Form, Cascader, Button } from 'antd';
const options = [
{
value: '1',
label: 'Option 1',
children: [
{
value: '1-1',
label: 'Option 1-1',
},
{
value: '1-2',
label: 'Option 1-2',
},
],
},
{
value: '2',
label: 'Option 2',
children: [
{
value: '2-1',
label: 'Option 2-1',
},
{
value: '2-2',
label: 'Option 2-2',
},
],
},
];
const MyModal = () => {
const [visible, setVisible] = useState(false);
const [form] = Form.useForm();
const showModal = () => {
// 设置默认值
form.setFieldsValue({
cascader: ['1', '1-1'], // 设置级联选择器的默认值
});
setVisible(true);
};
const handleOk = () => {
form.validateFields().then((values) => {
console.log(values);
setVisible(false);
});
};
const handleCancel = () => {
setVisible(false);
};
return (
);
};
export default MyModal;
在上述代码中,我们使用了Antd的Modal
、Form
、Cascader
和Button
组件。在点击按钮打开模态框时,执行showModal
函数。在showModal
函数中,我们使用form.setFieldsValue
方法设置级联选择器的默认值。
当点击模态框的确认按钮时,执行handleOk
函数。在handleOk
函数中,我们使用form.validateFields
方法来验证表单字段,并获取表单的值。