在写项目遇到动态新增一整个form表单的需求,当时还遇到坑了,没有get到正确的姿式,因此解决问题就想着写这个文章记录一下。
简易版在线demo:https://stackblitz.com/edit/react-x435fn?embed=1&file=index.jsreact
由于form里面的数据还须要正则校验之类的,为了方便,因此打算使用antd的form来写。
form经过数据遍历出来,每一个form均可以删除,也能够新增form。
最终实现效果如图:api
当删除一个form时,form中删除的数据出错。并且,每一个form的数据还须要函数二次处理。antd
解决:当时getFieldDecorator的写法不是很正确,应该按照下图这么写 getFieldDecorator(content[${index}].source
)
这样就把每一个form的数据保存在对应的content[index]中,而且form里每项的数据格式也对应了(content[index].xx)。函数
arr.map((item,index)=>( <div className={styles.content} key={index}> <Icon type="close" className={styles.close} onClick={deleteContent.bind(this,index)}/> <Form {...formItemLayout}> <Form.Item style={{ width: '50%' }} label="xxx"> {getFieldDecorator(`content[${index}].source`, { initialValue: item.source, rules: [], })(<Input placeholder="xxx" />)} </Form.Item> ...
这样解决了正确在遍历出来的form里存储数据的问题,如今要以前删除form以后,数据出错的问题。其实有了上面的修改,这步就简单多了。
一、使用form提供的api getFieldValue 获取到整个content数据
二、setFieldsValue,能够设置form的值。使用filter把要删除的数据过滤掉
三、把arr里的要删除的form也删掉,由于form是经过arr遍历出来的。arr.splice(index,1)this
const deleteContent = (index)=>{ confirm({ title: '肯定要删除吗?', onOk() { const content = form.getFieldValue('content'); form.setFieldsValue({ content: content.filter((item, key) => key !== index), }); arr.splice(index,1) dispatch({ type: 'xxx/updateStates', payload: { arr } }) }, onCancel() {}, }); }
好了,写到这里就结束了。但愿有帮到你们,这里最主要的是若是使用数据来遍历form,就最好把getFieldDecorator写成这种格式dataName[${index}].xx
spa