响应绑定到复选框并根据选中的

时间:2017-03-08 04:18:58

标签: javascript reactjs

尝试选中复选框,您将看到未定义。这很奇怪,我认为我正确地使用了find。或者有更好的方法吗?

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){
        console.log(key)

    console.log(e.target.checked)

const newFruitsData = this.state.fruits.find(obj => {
  obj.name === key ? obj.value = e.target.checked : ''

});
console.log(newFruitsData) //why this is 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>
    );
  }
}

2 个答案:

答案 0 :(得分:0)

你的find没有return语句,它总是返回undefined,而它应该返回boolean

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

答案 1 :(得分:0)

在handleChange()中,Array.prototype.find应该返回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)
}

你应该使用setState()代替,这是我的观点

---更新

http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf