如何将值设置为true选中,将false设置为unchecked

时间:2020-08-03 00:19:51

标签: javascript reactjs

我正在开发一个带复选框的React应用。我想包括一个复选框,该复选框在选中时发送true,在未选中时发送false。我的onChange是:

handleChange = (e) => {
    this.setState({
        [e.target.id]: e.target.value
    })
}

输入为:

<label>
   <input type="checkbox" class="filled-in" value="true" id="My Value" 
     onChange={this.handleChange} />
    <span>My Value</span>
</label>

我的州有:

   state = {
        My Value = ''
             }

当我提交并选中复选框时,它可以正常工作。问题是当我选中和取消选中时,该值保持为true而不是更改为false。我怎样才能解决这个问题。请帮忙。

谢谢。

2 个答案:

答案 0 :(得分:1)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 4 9 | 2 0 6 | 0 0 7 更改为value="true"

答案 1 :(得分:1)

更新处理程序以使用事件中的检查值

handleChange = e => {
  this.setState({
    [e.target.id]: e.target.checked
  });
};

不要对输入的检查值进行硬编码

<label>
  <input
    type="checkbox"
    className="filled-in"
    value={this.state['My Value']}
    id="My Value"
    onChange={this.handleChange}
  />
  <span>My Value</span>
</label>