Antd中如何默认保留该字段而不添加?
How to keep the field in Antd by default without adding it?
在 React 项目中,使用 Antd 作为设计框架,Form 组件具有单击按钮添加新字段的功能,但是,根据需要,需要进行一些更改,例如,字段应该已经存在可用而不是添加新的。前往下面的代码以供参考。
- 表单组件
<Form
name="dynamic_form_item"
{...formItemLayoutWithOutLabel}
onFinish={onFinish}
>
<Form.List name="names">
{(fields, { add, remove }, { errors }) => (
<Form.Item>
{/* This field should be already available instead of clicking 'Add Field' button */}
<Form.Item
{...field}
validateTrigger={["onChange", "onBlur"]}
noStyle
>
<Input
placeholder="passenger name"
style={{ width: "60%" }}
/>
</Form.Item>
<Button
type="dashed"
onClick={() => add()}
style={{ width: "60%" }}
icon={<PlusOutlined />}
>
Add field
</Button>
<Form.ErrorList errors={errors} />
</Form.Item>
)}
</Form.List>
</Form>
什么是合适的解决方案?
请参考codesandbox link: https://codesandbox.io/s/dynamic-form-item-antd4169-forked-dl8od
如果您的需求只是一次添加两个字段,可以通过修改加号按钮的 onClick 函数来实现:
<Button
type="dashed"
onClick={() => {
add();
add();
}}
style={{ width: "60%" }}
icon={<PlusOutlined />}
>
Add field
</Button>;
Add
函数支持配置初始值。
只需将 initialValues
属性添加到 Form 标签。
<Form
name="dynamic_form_item"
{...formItemLayoutWithOutLabel}
initialValues={{ names: [""] }}
onFinish={onFinish}
>
在 React 项目中,使用 Antd 作为设计框架,Form 组件具有单击按钮添加新字段的功能,但是,根据需要,需要进行一些更改,例如,字段应该已经存在可用而不是添加新的。前往下面的代码以供参考。
- 表单组件
<Form
name="dynamic_form_item"
{...formItemLayoutWithOutLabel}
onFinish={onFinish}
>
<Form.List name="names">
{(fields, { add, remove }, { errors }) => (
<Form.Item>
{/* This field should be already available instead of clicking 'Add Field' button */}
<Form.Item
{...field}
validateTrigger={["onChange", "onBlur"]}
noStyle
>
<Input
placeholder="passenger name"
style={{ width: "60%" }}
/>
</Form.Item>
<Button
type="dashed"
onClick={() => add()}
style={{ width: "60%" }}
icon={<PlusOutlined />}
>
Add field
</Button>
<Form.ErrorList errors={errors} />
</Form.Item>
)}
</Form.List>
</Form>
什么是合适的解决方案? 请参考codesandbox link: https://codesandbox.io/s/dynamic-form-item-antd4169-forked-dl8od
如果您的需求只是一次添加两个字段,可以通过修改加号按钮的 onClick 函数来实现:
<Button
type="dashed"
onClick={() => {
add();
add();
}}
style={{ width: "60%" }}
icon={<PlusOutlined />}
>
Add field
</Button>;
Add
函数支持配置初始值。
只需将 initialValues
属性添加到 Form 标签。
<Form
name="dynamic_form_item"
{...formItemLayoutWithOutLabel}
initialValues={{ names: [""] }}
onFinish={onFinish}
>