React的 FormList 怎么绑定明细并自动带出来
在React中,可以使用Form.List来绑定明细,并自动带出来。
首先,需要使用Form.create方法创建一个表单组件,然后在表单中使用Form.List来绑定明细数据。Form.List是一个高阶组件,可以将一个数组字段绑定到表单中,以便处理动态的表单项。
以下是一个使用Form.List的例子:
import React from 'react';
import { Form, Input, Button } from 'antd';
class MyForm extends React.Component {
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator, getFieldValue } = this.props.form;
getFieldDecorator('details', { initialValue: [] });
const details = getFieldValue('details');
const addDetail = () => {
const newDetails = [...details, {}];
this.props.form.setFieldsValue({ details: newDetails });
};
const removeDetail = index => {
const newDetails = [...details];
newDetails.splice(index, 1);
this.props.form.setFieldsValue({ details: newDetails });
};
return (
<Form onSubmit={this.handleSubmit}>
{details.map((detail, index) => (
<Form.Item key={index}>
{getFieldDecorator(`details[${index}].name`, {
rules: [{ required: true, message: 'Please input detail name' }],
})(<Input placeholder="Detail Name" />)}
{details.length > 1 ? (
<Button type="danger" onClick={() => removeDetail(index)}>
Remove
</Button>
) : null}
</Form.Item>
))}
<Form.Item>
<Button type="primary" onClick={addDetail}>
Add Detail
</Button>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
}
}
const WrappedMyForm = Form.create()(MyForm);
export default WrappedMyForm;
在上面的例子中,details是一个数组字段,用于存储明细数据。通过getFieldDecorator方法来绑定details字段到表单中,并设置验证规则。在addDetail方法中,通过setFieldsValue方法来更新details的值,以便触发表单重新渲染。
这样,当点击"Add Detail"按钮时,会动态添加一个明细项到表单中,并且可以自动带出明细项的值。点击"Remove"按钮可以删除对应的明细项。
在表单提交时,可以通过this.props.form.validateFields方法来验证表单并获取表单的值。
希望以上信息能对您有所帮助
原文地址: https://www.cveoy.top/t/topic/iVMG 著作权归作者所有。请勿转载和采集!