【发布时间】:2021-02-01 07:09:10
【问题描述】:
我试图在单击相应按钮时显示相应的<div>。基本上我想在单击相应按钮时显示hey man! 和hey woman!。
所以,我有两个这样的按钮:
<div className="row">
<button className="btn col-6 bg-transparent col-12 col-sm-6" onclick={() => this.togglediv("showdiv1")} >
<img className="humanbody profile" src={malebody} />
</button>
<button className="btn col-6 bg-transparent col-12 col-sm-6" onclick={() => this.togglediv("showdiv2")} >
<img className="humanbody profile" src={femalebody} alt="" />
</button>
</div>
这里使用以下代码处理 onclick 事件:
class Home extends React.Component {
constructor() {
super();
this.state = {
showdiv1: false,
showdiv2: false
};
this.togglediv = this.togglediv.bind(this);
}
togglediv(div_name) {
switch (div_name) {
case "showdiv1":
this.setState({ showdiv1: !this.state.showdiv1 });
break;
case "showdiv2":
this.setState({ showdiv2: !this.state.showdiv2 });
break;
}
}
render() {
const { showdiv1, showdiv2 } = this.state;
return (
<div className="container py-5">
<div className="row">
<button className="btn col-6 bg-transparent col-12 col-sm-6" onclick={() => this.togglediv("showdiv1")} >
<img className="humanbody profile" src={malebody} />
</button>
<button className="btn col-6 bg-transparent col-12 col-sm-6" onclick={() => this.togglediv("showdiv2")} >
<img className="humanbody profile" src={femalebody} />
</button>
</div>
{/* Hidden div */}
<div className="row">
{
showdiv1 && (
<div>
Hey man!
</div>
)
}
{
showdiv2 && (
<div>
Hey woman!
</div>
)
}
</div>
{/* Hidden div */}
</div>
)
}
}
export default Home;
点击按钮时隐藏的分区不会出现在屏幕上。
编辑:我错误地在代码中写了onlcick 代替了onClick,在更正后,它工作正常。
【问题讨论】:
-
那为什么要隐藏
class=row呢? -
你没有重新显示隐藏的
row
标签: javascript css reactjs