首页 > 解决方案 > 如何在输入复选框中检索值(使用 Reactjs)

问题描述

我知道这是其他人的重复问题,但是我有问题为什么他们在我的控制台中没有值输出。

我的目标:我想获得复选框的值。

我这里有我的代码。

状态:

employ_status:''

构造函数:

this.handle_employ_status = this.handle_employ_relocate.bind(this);

处理:

handle_employ_status(e){
        console.log(e.target.checked, e.target.name);
    }

JSX:

<div className="form-check-inline disabled">
    <label className="form-check-label">
        <input 
        type="checkbox" 
        className="form-check-input" 
        name="employmentstatus"
        onChange={this.handle_employ_status} 
        defaultChecked={false} 
        value="Self-Employed"/>Self-Employed
    </label>
</div>
<div className="form-check-inline disabled">
    <label className="form-check-label">
        <input 
        type="checkbox" 
        className="form-check-input" 
        name="employmentstatus" 
        onChange={this.handle_employ_status}
        defaultChecked={false}  
        value="Student"/>Student
    </label>
</div>

安慰:

console.log(this.state.employ_status);

标签: javascriptreactjs

解决方案


在你的构造函数中

this.handle_employ_status = this.handle_employ_relocate.bind(this);

应该替换为

this.handle_employ_status = this.handle_employ_status.bind(this);

推荐阅读