...
const xxx = ()=>{
let value= 1
const fields = form.getFieldsValue();
const { names } = fields;
Object.assign(names[index], { checked:value });
form.setFieldsValue({ names });
}
....
<Form
name="selects"
onFinish={onFinish}
autoComplete="off"
form={form}
labelCol={{ span: 6 }}
wrapperCol={{ span: 16 }}
>
....
<Form.List
name="names"
rules={[
{
validator: async (_, names) => {
if (!names || names.length < 2) {
return Promise.reject(new Error('至少两个选项'));
}
},
},
]}
>
{(fields, { add, remove }, { errors }) => (
<>
{fields.map(({ key, name, ...restField }, index) => (
<Space
key={index}
style={{
display: 'flex',
marginBottom: 8,
}}
align="baseline"
>
<Form.Item
{...restField}
label={ topicList[index]}
name={[index, 'first']}
rules={[
{
required: true,
message: '请输入' + topicList[index],
},
]}
>
<Input placeholder={'请输入' + topicList[index]} />
</Form.Item>
<Form.Item
{...restField}
label="类型"
name={[index, 'last']}
rules={[
{
required: true,
message: '请选择',
},
]}
>
<Input placeholder={'请输入' + topicList[index]} />
</Form.Item>
//hidden 隐藏Form.Item
<Form.Item hidden name={[index, 'checked']}>
<Input />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(index)} />
</Space>
))}
<Form.Item>
<Button
type="dashed"
onClick={() => add()}
block
icon={<PlusOutlined />}
disabled={fields.length >= 4}
>
添加
</Button>
<Form.ErrorList errors={errors} />
</Form.Item>
</>
)}
</Form.List>
....
Antd表单列表创建一个item对象数组。则有必要定位对象在数组中的位置,该数组包含将改变值的项。
返回表单项的所有值:
const fields = form.getFieldsValue()
检索包含表单列表对象的数组:
const {names} = fields
传递对象在数组中的位置,并将该项更改为新值:
Object.assign(names[key], {checked: value})
然后将新的数组值传递给表单:
form.setFieldsValue({names})