Ger*_*ann 7 javascript reactjs antd
对于某人来说,这可能是一件容易的事。在 AntD 的表单文档和演示中,他们的演示一开始没有字段。您必须单击动态表单的“+ 添加字段”按钮才能添加并显示第一个字段,如下所示。
如果我希望它从显示第一个字段开始,而不必先单击“+ 添加字段”按钮,该怎么做?似乎我需要在渲染时以某种方式调用 add 函数?无论如何,我正在寻找它在最初加载表单时向第一位乘客显示,例如在我按下“添加字段”按钮后的屏幕截图中。
换句话说,我希望始终至少有 1 名乘客。
他们的演示代码可以在上面的链接中查看,该链接可以让您直接访问他们的文档,但也在这里:
import { Form, Input, Button } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
const DynamicFieldSet = () => {
const onFinish = values => {
console.log('Received values of form:', values);
};
return (
<Form name="dynamic_form_item" {...formItemLayoutWithOutLabel} onFinish={onFinish}>
<Form.List name="names">
{(fields, { add, remove }) => {
return (
<div>
{fields.map((field, index) => (
<Form.Item
{...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
label={index === 0 ? 'Passengers' : ''}
required={false}
key={field.key}
>
<Form.Item
{...field}
validateTrigger={['onChange', 'onBlur']}
rules={[
{
required: true,
whitespace: true,
message: "Please input passenger's name or delete this field.",
},
]}
noStyle
>
<Input placeholder="passenger name" style={{ width: '60%' }} />
</Form.Item>
{fields.length > 1 ? (
<MinusCircleOutlined
className="dynamic-delete-button"
style={{ margin: '0 8px' }}
onClick={() => {
remove(field.name);
}}
/>
) : null}
</Form.Item>
))}
<Form.Item>
<Button
type="dashed"
onClick={() => {
add();
}}
style={{ width: '60%' }}
>
<PlusOutlined /> Add field
</Button>
</Form.Item>
</div>
);
}}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<DynamicFieldSet />, mountNode);
.dynamic-delete-button {
cursor: pointer;
position: relative;
top: 4px;
font-size: 24px;
color: #999;
transition: all 0.3s;
}
.dynamic-delete-button:hover {
color: #777;
}
.dynamic-delete-button[disabled] {
cursor: not-allowed;
opacity: 0.5;
}
Run Code Online (Sandbox Code Playgroud)
Ham*_*ani 10
你可以使用initialValues道具。看一下这个例子:
https://codesandbox.io/s/dynamic-form-item-ant-design-demo-qm1d8
| 归档时间: |
|
| 查看次数: |
6489 次 |
| 最近记录: |