gpt4 book ai didi

javascript - 根据按钮显示特定元素

转载 作者:行者123 更新时间:2023-12-03 02:33:57 25 4
gpt4 key购买 nike

我需要使用四个按钮来过滤它,在同一页面上显示不同的元素。如果我点击NavigationBar组件的第一个按钮,则必须显示一个特定的div。

我有一个必须显示不同元素的主页:

class Home extends Component {

constructor(props) {
super(props);
}

showContent() {
alert('ok');
}

render() {
return (
<div className="container">
<Header activeLink={['home']}/>
<p>Some texte here</p>
<NavigationBar onClick={this.showContent} firstSection="L'entreprise" secondSection="Pourquoi nous choisir ?"/>
<Footer/>
</div>
);
}
}

export default Home;

我的 NavigationBar 组件带有四个按钮:

class NavigationBar extends Component {

constructor(props) {
super(props);
}

render() {
return (
<div className="navigation-bar flex row between">
<div onClick={() => {this.props.onClick()}}>
<p>{this.props.firstSection}</p>
</div>
<div onClick={() => {this.props.onClick()}}>
<p>{this.props.secondSection}</p>
</div>
<div onClick={() => {this.props.onClick()}}>
<p>{this.props.thirdSection}</p>
</div>
<div onClick={() => {this.props.onClick()}}>
<p>{this.props.fourthSection}</p>
</div>
</div>
);
}
}

export default NavigationBar;

使用此代码,当我单击导航栏组件的 div 时,我可以显示警报('ok'),但我不知道如何识别单击了哪个 div。如果我知道如何做到这一点,我可以轻松地显示特定元素。感谢您的帮助。

最佳答案

onClick 处理程序将为您提供一个事件对象。将该事件对象传递回showContent 。您还可以向元素添加标识信息:

<div data-key="foo" onClick={e => this.props.onClick(e)}>

然后:

showContent(e) {
console.log(e.target.getAttribute('data-key'));
}

关于javascript - 根据按钮显示特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48613138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com