首页 > 解决方案 > 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>

enter image description here

标签: reactjs

解决方案


您在这里缺少关键因素,处理更改适用于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()
            }]
    })

}

注意:您可以按照另一种方法更新数据,但需要为每个新组件创建一个本地状态,但是,这应该可以正常工作

演示脚本


推荐阅读