Html 在复选框上显示组件单击“反应”
您好,我是react新手,我对react中的复选框单击处理有问题。我想在选中复选框时显示一个div,如果未选中复选框,则删除该div 我这样做的方式仅在单击复选框时显示div,而在取消选中时不删除div。我怎样才能在反应中做到这一点Html 在复选框上显示组件单击“反应”,html,css,reactjs,checkbox,Html,Css,Reactjs,Checkbox,您好,我是react新手,我对react中的复选框单击处理有问题。我想在选中复选框时显示一个div,如果未选中复选框,则删除该div 我这样做的方式仅在单击复选框时显示div,而在取消选中时不删除div。我怎样才能在反应中做到这一点 class QuestionOverlay extends Component { constructor() { super(); this.showComments = this.showComments.bind(
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}
)
}
}
类覆盖扩展组件{
构造函数(){
超级();
this.showcoments=this.showcoments.bind(this);
此.state={
showComponent:false,
};
}
showComments=(e)=>{
这是我的国家({
showComponent:对,
});
}
render(){
返回(
启用注释
{this.state.showComponent?:null}
)
}
}
您需要将onClick
侦听器更改为onChange
。然后,将showcoments
重命名为toggleComments
,并按如下方式实现:
toggleComments(e) {
this.setState({ showComponent: e.target.checked });
}
您需要将
onClick
侦听器更改为onChange
。然后,将showcoments
重命名为toggleComments
,并按如下方式实现:
toggleComments(e) {
this.setState({ showComponent: e.target.checked });
}
原因是您总是设置
showComponent=true
的值,当复选框未选中时,您需要重置状态变量,请使用以下方法:
showComments(e){
this.setState({
showComponent: e.target.checked,
});
}
检查工作小提琴:
你需要改变的事情很少:
*您将从渲染返回2个元素,从条件渲染返回一个div
,再返回一个div
。我们不能从render
返回多个html
元素,因此将条件呈现放在主div
中
*您将绑定showcoments
方法两次,一次在构造函数中,另一次使用箭头
,删除不需要的箭头
*如果条件为空,请在其中放入一些内容。原因是您总是设置showComponent=true
的值,当复选框未选中时,需要重置状态变量,请使用以下方法:
showComments(e){
this.setState({
showComponent: e.target.checked,
});
}
检查工作小提琴:
你需要改变的事情很少:
*您将从渲染返回2个元素,从条件渲染返回一个div
,再返回一个div
。我们不能从render
返回多个html
元素,因此将条件呈现放在主div
中
*您将绑定showcoments
方法两次,一次在构造函数中,另一次使用箭头
,删除不需要的箭头
*您在条件下渲染的Div为空,请在其中放入一些内容。以下是代码中的几个语法错误:
在类中定义的函数不能使用=
方式
React render函数需要一个根容器,如div
tag
const{Component}=React;
const{render}=ReactDOM;
类覆盖扩展组件{
建造师(道具){
超级(道具);
此.state={
showComponent:false
}
this.showcoments=this.showcoments.bind(this);
}
showComments(){
这是我的国家({
showComponent:!this.state.showComponent
});
}
render(){
返回(
启用注释
{this.state.showComponent?注释:null}
);
}
}
渲染(
,
document.getElementById('root'))
);代码>
以下是代码中的几个语法错误:
在类中定义的函数不能使用=
方式
React render函数需要一个根容器,如div
tag
const{Component}=React;
const{render}=ReactDOM;
类覆盖扩展组件{
建造师(道具){
超级(道具);
此.state={
showComponent:false
}
this.showcoments=this.showcoments.bind(this);
}
showComments(){
这是我的国家({
showComponent:!this.state.showComponent
});
}
render(){
返回(
启用注释
{this.state.showComponent?注释:null}
);
}
}
渲染(
,
document.getElementById('root'))
);代码>
很高兴,帮助您:)很高兴,帮助您:)它有一个根容器。我只是没有把它包括在这里,因为我的问题不需要它。它有一个根容器。我只是没有把它包括在这里,因为我的问题不需要它