reactjs - How to handle form object in array to add list
问题描述
i have a problem when i create an Array and i put object to array, when i create handleform Function, the field cannot typing, just return null, i dont know why, i follow the intruction from guy on stackoverflow too.
this.state = {
post : [],
isChecked : false,
list : [],
object : {
email : '',
password : ''
}
}
handleForm = (e) => {
let newObject = {...this.state.object};
newObject[e.target.name] = e.target.value;
this.setState({
object : newObject
})
}
handleAdd = (e) => {
this.setState({
list : [...this.state.list, this.state.object]
})
}
mycomponent
<Form onSubmit={handleSubmit}>
{
list.map(h => (
<FormGroup key = "i">
<FormGroup >
<Label for="email">Email</Label>
<Input onChange={handleForm} value={h.email} type="email" name = "email" className="form-control" placeholder="Email" required="" />
</FormGroup>
<FormGroup >
<Label htmlFor="password">Password</Label>
<Input onChange={handleForm} value={h.password} type="password" name = "password" className="form-control" placeholder="Password" required="" />
</FormGroup>
</FormGroup>
))}
<FormGroup>
<ButtonAntd type="primary" className="text right" onClick={handleAdd}>+</ButtonAntd>{' '}
</FormGroup>
<FormGroup >
<label>
<input type="checkbox" checked={isChecked} onChange = {toggleChange} value="isChecked"/>{' '}
Anda yakin, Data anda sudah benar ?
</label>
</FormGroup>
<ButtonAntd type="primary" htmlType="submit" >Submit</ButtonAntd> {' '}
<ButtonAntd type="danger" onClick={handleBatal} >Batal</ButtonAntd>
</Form>
解决方案
您在这里缺少关键因素,处理更改适用于object
状态以及来自列表的表单字段和值,因此要解决此问题,您需要为每个列表对象提供一个 id,然后当发生更改时您用 id 更新匹配的对象并更新它的字段:
import shortid from 'shortid'
// the rest of your code here
handleForm = ({ target: { name, value, id } }) => {
const newList = list.map(obj => {
if (obj.id === id)
return { ...obj, [name]: value }
return obj
})
this.setState({
list: newList
})
}
handleAdd = (e) => {
this.setState({
list: [
...this.state.list,
{
...this.state.object,
id: shortid.generate()
}]
})
}
注意:您可以按照另一种方法更新数据,但需要为每个新组件创建一个本地状态,但是,这应该可以正常工作
推荐阅读
- reactjs - 从后端获取更新或更新 redux
- android - Unity - Android - 确定是否启用了“退出广告个性化”?
- java - 解码并写入磁盘后无法打开图像
- java - 如何在java中获取最后修改和当前的sysdate时间差
- python - 如何在 Python 中从文件中读取 dict 数据并转换为 JSON
- php - PHP preg_replace 在没有字符串的地方插入一个字符串
- python - Python:紧凑且可逆地将大整数编码为具有可变或固定长度的base64或base16
- android - LinearLayout 未显示其所有子项
- winforms - 如果选中了前一个窗口上的复选框,如何在树视图中设置节点以开始检查
- javascript - 构建同构 React 应用程序时如何处理 SASS 的导入?