简体   繁体   中英

react bind to checkbox and update state base on checked

Try to check the checkbox, you will see undefined. That's strange I think I used find properly. Or there's a better way to do it?

http://jsbin.com/ficijuwexa/1/edit?js,console,output

class HelloWorldComponent extends React.Component {

  constructor(){
    super()
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      "fruits":[
        {"name":"banana","value":true},
        {"name":"watermelon","value":false},
        {"name":"lemon","value":true},
      ]
    }
  }

  handleChange(e,key){        
    const newFruitsData = this.state.fruits.find(obj => {
        obj.name === key ? obj.value = e.target.checked : ''
    });
    console.log(newFruitsData) // <-- why does this output undefined?
  }

  render() {
    return (
      <div>
        {this.state.fruits.map(obj => 
           <div key={obj.name}>
           <label>{obj.name}</label>
           <input onChange={(e) => this.handleChange(e, obj.name)} type="checkbox" defaultChecked={obj.value} />
            </div>
         )}
         <br />
         <pre>{JSON.stringify(this.state.fruits,null,2)}</pre>
       </div>
    );
  }
}

您的发现没有return语句,它总是返回undefined,而应该返回boolean

const newFruitsData = this.state.fruits.find(obj => obj.name === key && obj.value === e.target.checked);

In the handleChange(), the Array.prototype.find should return Bool:

handleChange(e,key){
    let nxState = Object.assign({}, this.state)
    nxState.fruits.find(obj => {
      if (obj.name === key) {
        obj.value = e.target.checked
        return true
      } else {
        return false
      }
    });
    this.setState(nxState)
}

And you should use setState() instead, it's my opinion of course

--- Update

Check it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM