我真的对这段代码中发生的事情感到困惑。我想在 ReactJS 中有一个复选框。该框不会选中/取消选中 onClick,但它会将您的选择保存为 true/false。
非常感谢您的帮助,如有必要,我可以详细说明。
屏幕截图 - 复选框从未被选中,即使您单击它并且值已从 false 更改为 true
export default class checkboxEdit extends Component { //sample change
constructor(props){
super(props);
this.onChangeHandler = this.onChangeHandler.bind(this);
this.onBlur = this.onBlur.bind(this);
}
onChangeHandler(event){
event.preventDefault()
this.props.onChange({
target:{
value: event.target.checked
}
});
if (this.props.onClick && Object.prototype.toString.call(this.props.onClick) == '[object Function]') {
try {
this.props.onClick(event);
} catch (err) {
console.log('Suppressing error', err);
}
}
}
onBlur(event) {
if (this.props.onBlur && Object.prototype.toString.call(this.props.onBlur) == '[object Function]') {
this.props.onBlur(event);
}
if (this.props.onBlurChange && Object.prototype.toString.call(this.props.onBlurChange ) == '[object Function]') {
this.props.onBlurChange (event);
}
}
render() {
return (
<p className='form-control-static'>
<span className='checkbox'>
<label style={{minWidth:'50px'}} className='checkbox'>
<input style={{minWidth:'50px'}} type='checkbox'
onMouseEnter={this.props.onMouseOver}
onMouseLeave={this.props.onMouseOut}
onChange={this.onChangeHandler}
onBlur={this.onBlur}
onFocus={this.props.onFocus}
aria-required={(this.props.required) ? true : false}
value="on"
checked={(this.props.value) ? "checked" : ""}
className='form-check-input'
/>
<span>{this.props.checkboxText}</span>
</label>
<small className='form-text text-muted'>{this.props.descriptiveText}</small>
</span>
</p>
);
}
}
最佳答案
如文档中所示,checked
属性应该是 bool 值而不是字符串。所以你可以试试:
checked={this.props.value}
此外,我不确定 value
属性的存在是否会导致您的问题。您可以尝试将其删除。
编辑
在您的处理程序中调用 event.preventDefault
显然破坏了 react 更新的正常工作。参见 https://stackblitz.com/edit/react-t2he58?embed=1&file=CheckBoxEdit.js一个工作解决方案。
关于javascript - ReactJS 中的复选框问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45550353/