有一种迷茫叫一脸懵逼,当明白真相时恍然大悟。
在ant design的官网中有一个demo叫动态增减表单项,非常方便的使用在动态增加选项的功能,但是并没有提供设置默认值,而且在所有使用Form.List的demo中,也都没有。!_! 一脸懵逼的表示,怎么展现默认值啊。
官网的DEMO
demo的样例代码为
<Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off" >
<Form.List name="users">
{(fields, { add, remove }) => {
return (
<div>
{fields.map(field => (
<Space key={field.key} style={{ display: 'flex', marginBottom: 8 }} align="start">
<Form.Item
{...field}
name={[field.name, 'startTime']}
fieldKey={[field.fieldKey, 'startTime']}
rules={[{ required: true, message: 'Missing first name' }]}
>
<Input placeholder="First Name" />
</Form.Item>
<Form.Item
{...field}
name={[field.name, 'endTime']}
fieldKey={[field.fieldKey, 'endTime']}
rules={[{ required: true, message: 'Missing last name' }]}
>
<Input placeholder="Last Name" />
</Form.Item>
<MinusCircleOutlined
onClick={() => {
remove(field.name);
}}
/>
</Space>
))}
<Form.Item>
<Button
type="dashed"
onClick={() => {
add();
}}
block
>
<PlusOutlined /> Add field
</Button>
</Form.Item>
</div>
);
}}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
展示的效果为
设置默认值
在antd的4.x版本中,在form层级上使用initialValues来设置默认值。
<Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off" initialValues={{"users": [{
fieldKey: 0,
isListField: true,
key: 0,
name: 0,
endTime: "14:48",
startTime: "14:48",
}, {
fieldKey: 1,
isListField: true,
key: 1,
endTime: "14:48",
startTime: "14:48",
name: 1
}]}}>
添加了initialValues并为name为“users”的Form.List设置默认值。完整的代码为
<Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off" initialValues={{"users": [{
fieldKey: 0,
isListField: true,
key: 0,
name: 0,
endTime: "14:48",
startTime: "14:48",
}, {
fieldKey: 1,
isListField: true,
key: 1,
endTime: "14:48",
startTime: "14:48",
name: 1
}]}}>
<Form.List name="users">
{(fields, { add, remove }) => {
return (
<div>
{fields.map(field => (
<Space key={field.key} style={{ display: 'flex', marginBottom: 8 }} align="start">
<Form.Item
{...field}
name={[field.name, 'startTime']}
fieldKey={[field.fieldKey, 'startTime']}
rules={[{ required: true, message: 'Missing first name' }]}
>
<Input placeholder="First Name" />
</Form.Item>
<Form.Item
{...field}
name={[field.name, 'endTime']}
fieldKey={[field.fieldKey, 'last']}
rules={[{ required: true, message: 'Missing last name' }]}
>
<Input placeholder="Last Name" />
</Form.Item>
<MinusCircleOutlined
onClick={() => {
remove(field.name);
}}
/>
</Space>
))}
<Form.Item>
<Button
type="dashed"
onClick={() => {
add();
}}
block
>
<PlusOutlined /> Add field
</Button>
</Form.Item>
</div>
);
}}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
运行的默认效果为:
不明白时千难万难,举步维艰。当看到真相的时候,一马平川,神清气爽!!!
// END 喜欢秋天的风,带着点点的果香