在 React.js 中检索复选框的值

新手上路,请多包涵

我想在选中时检索我的复选框的值。

我正在使用这个“ http://react-component.github.io/checkbox/ ”。

我的代码看起来像这样。

 <div className="user_box">
    { check.map((values , i)=> {
        return <Checkbox
            name = "checkbox"
            onChange={this.checkvalue.bind(this)}
            value={values.username}
        />
    })}
</div>

我的功能:

 checkvalue(e){
    // var all_users = [];
    // var value = this.checkbox.value;
    // all_users.push(value);
    // console.log(all_users);

    console.log('checkbox checked:', (e.target.checked));
}

我不明白如何检索复选框的值。

原文由 Manpreet Oberoi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 275
2 个回答

您需要将“e,合成事件参数传递给您的处理程序”:

 handleChange(e) {
  let isChecked = e.target.checked;
  // do whatever you want with isChecked value
}

render() {
  // ... your code here
  return (
    {/* your other jsx here */}
    <Checkbox otherProps onChange={e => this.handleChange(e)} />
    {/* your other jsx here */}
  );
}

原文由 erdysson 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用合成事件参数,这里是一个例子:

 const element1 = "boy";
const element2 = "girl";

<input
 type="checkbox"
 name={element1}
 value={element1}
 onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
 </label>

<input
 type="checkbox"
 name={element2}
 value={element2}
 onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
 </label>

handleChange = (e) => {
// to find out if it's checked or not; returns true or false
const checked = e.target.checked;

// to get the checked value
const checkedValue = e.target.value;

// to get the checked name
const checkedName = e.target.name;

//then you can do with the value all you want to do with it.
};

原文由 Anayo Oleru 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题