[英]Checkbox don't show checked
I'm working with checkbox input. 我正在使用复选框输入。 When I click on checbox, checkbox don't show checked but checkbox's value I still get.
当我单击checbox时,checkbox不会显示为已选中,但我仍然会得到checkbox的值。 I use React JS
我使用React JS
import React from 'react';
import callApi from './../../utils/apiCaller'
import { Link } from 'react-router-dom'
class ProductActionPage extends React.Component {
constructor(props) {
super(props);
this.state = {
id: '',
productStatus: ''
}
}
onChange = (e) => {
var target = e.target;
var name = target.name;
var value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({
[name]: value
});
}
render() {
var statusCheckbox = this.state.productStatus === 'true' ? true : false;
return (
<div className="row">
<div className="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<div className="form-group">
<label>Trang thai: </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" checked={statusCheckbox} name="productStatus" onChange={this.onChange} />
Con hang
</label>
</div>
<button type="submit" className="btn btn-primary">Luu lai</button>
<Link to="/product/list" className="btn btn-danger ml-5">Huy bo</Link>
</div>
</div>
);
}
}
How can I show checked checkbox? 如何显示已选中的复选框?
this.state.productStatus
is a boolean value, so your condition will always give you the false
, because you are comparing Boolean === String
. this.state.productStatus
是一个布尔值,因此您的条件将始终为false
,因为您正在比较Boolean === String
。
Just change 只是改变
var statusCheckbox = this.state.productStatus === 'true' ? true : false;
to 至
var statusCheckbox = this.state.productStatus ? true : false; //It doesn't make any sense
Or simply 或者简单地
var statusCheckbox = this.state.productStatus;
Or you can directly use this.state.productStatus
, 或者,您可以直接使用
this.state.productStatus
,
<input
type="checkbox"
checked={this.state.productStatus}
name="productStatus"
onChange={this.onChange}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.