你好,我是 React 的新手,我有一个关于 React 中的复选框点击处理的问题。我想在选中复选框时显示一个 div,如果未选中该复选框,则删除该 div。
我这样做的方式仅在单击复选框时显示 div,但在取消选中时不会删除 div。我怎样才能在 react 中做到这一点?
class QuestionOverlay extends Component {
constructor() {
super();
this.showComments = this.showComments.bind(this);
this.state = {
showComponent: false,
};
}
showComments = (e) => {
this.setState({
showComponent: true,
});
}
render() {
return (
<div className="add_checkbox">
<span>Enable Comments</span>
<input className="checkbox" type="checkbox" name="enable_comment" onClick={this.showComments} value="enable_comment"/>
</div>
{this.state.showComponent ? <div className="comments_preview_sample"></div> : null}
)
}
}
最佳答案
原因是你总是设置showComponent=true
的值,你需要在取消选中复选框时重置状态变量,使用这个:
showComments(e){
this.setState({
showComponent: e.target.checked,
});
}
检查工作 fiddle :https://jsfiddle.net/mrqutgbz/
您需要更改的几件事:
*您从 render
中返回
2 个元素,一个 div
和一个来自条件 的
。我们不能从 div
>呈现render
返回多个 html
元素,所以将条件渲染放在主 div
中。
*您两次绑定(bind)
showComments
方法,一次在constructor
中,另一次使用arrow
,删除箭头
,这不是必需的。
*您正在呈现
的条件是空的,将一些内容放入其中。
关于html - 在复选框上显示组件点击 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42267342/