[英]How to retrieve value in input checkbox (Using 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);
在您的构造函数中
this.handle_employ_status = this.handle_employ_relocate.bind(this);
应该替换为
this.handle_employ_status = this.handle_employ_status.bind(this);
您this
绑定到错误的处理程序:
this.handle_employ_status = this.handle_employ_relocate.bind(this);
应该:
this.handle_employ_status = this.handle_employ_status.bind(this);
如果使用箭头功能,则无需在构造函数中进行绑定
handle_employ_status = e => {
console.log(e.target.checked, e.target.name);
}
另外,要处理复选框值,您可以执行以下操作
constructor(){
this.state = {
empChecked: false,
stuChecked: true
}
}
handle_employ_status = e = {
if(e.target.value == "Self-Employed"){
this.setState({
empChecked: !this.state.empChecked
});
}
if(e.target.value == "Student"){
this.setState({
stuChecked: !this.state.stuChecked
});
}
console.log(e.target.checked, e.target.name);
}
<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}
checked={this.state.empChecked}
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}
checked={this.state.stuChecked}
value="Student"/>Student
</label>
</div>
这些是您的代码中的一些问题:
this.handle_employ_status = this.handle_employ_relocate.bind(this);
在此代码中, handle_employ_relocate
函数在哪里? handle_employ_relocate
函数,则需要更改句柄函数handle_employ_status(e){ //should be named by "handle_employ_relocate" console.log(e.target.checked, e.target.name); }
handle_employ_status(e){ //should be named by "handle_employ_relocate" console.log(e.target.checked, e.target.name); }
.jsx
文件中,如果您Control
组件,则应删除UnControl
属性: defaultChecked={false} //this line should be convert to checked={this.state.employ_status}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.