Form 表单 – Ant Design Mobile
antd mobile的表单组件中的自增表单数组Form.Array
数组组件中的值设如何设置(NamePath的格式)
单选框如何撤销?
如何动态控制子表单的字段显隐?
案例
import { Button, Form, Input, Radio } from antd-mobile ;
import { AddCircleOutline } from antd-mobile-icons ;
export default () => {
const [form] = Form.useForm();
const onFinish = (values: any) => {
console.log(values);
};
return (
<>
<Form
form={form}
onFinish={onFinish}
initialValues={{
contacts: [{}],
}}
footer={
<Button block type="submit" color="primary" size="large">
提交
</Button>
}
mode="card"
>
<Form.Item name={ name } label="客户名称">
<Input placeholder="请输入客户名称" />
</Form.Item>
<Form.Array
name="contacts"
onAdd={(operation) => operation.add({ name: 张三 })}
renderAdd={() => (
<span>
<AddCircleOutline /> 添加
</span>
)}
renderHeader={({ index }, { remove }) => (
<>
<span>联系人{index + 1}</span>
<a onClick={() => remove(index)} style={{ float: right }}>
删除
</a>
</>
)}
>
{(fields) =>
fields.map(({ index }) => (
<>
<Form.Item
name={[index, name ]}
label="姓名"
rules={[{ required: true, message: 姓名不能为空 }]}
>
<Input placeholder="请输入姓名" />
</Form.Item>
<Form.Item name={[index, address ]} label="地址">
<Input placeholder="请输入地址" />
</Form.Item>
{/* 根据contacts中的值控制表单显示 */}
<Form.Subscribe to={[ contacts ]}>
{({ contacts }) => {
// 有姓名才显示性别
if (contacts[index].name) {
return (
<>
<Form.Item
name={[index, sex ]}
label="性别"
rules={[{ required: false, message: 性别 }]}
>
<Radio.Group>
<Radio
key={1}
value={1}
onClick={() => {
// 点击可以撤销的单选
if (1 == contacts[index].sex) {
setTimeout(() => {
form.setFieldValue(
[ contacts , index, sex ],
null,
);
}, 50);
}
}}
>
男
</Radio>
<Radio
key={2}
value={2}
onClick={() => {
// 点击可以撤销的单选
if (2 == contacts[index].sex) {
setTimeout(() => {
form.setFieldValue(
[ contacts , index, sex ],
null,
);
}, 50);
}
}}
>
女
</Radio>
</Radio.Group>
</Form.Item>
</>
);
}
}}
</Form.Subscribe>
</>
))
}
</Form.Array>
</Form>
</>
);
};
Form.Array 中 NamePath的使用
form.setFieldValue([ contacts , index, name ], jack );
© 版权声明
文章版权归作者所有,未经允许请勿转载。如内容涉嫌侵权,请在本页底部进入<联系我们>进行举报投诉!
THE END
暂无评论内容