gpt4 book ai didi

javascript - 在 React 中为 child 或其相关 sibling 切换事件类 onClick

转载 作者:行者123 更新时间:2023-11-29 20:58:16 25 4
gpt4 key购买 nike

当我单击导航链接时,我可以成功地在 true 和 false 之间切换 state.navigation,然后在导航组件上设置类。

然而,它只会更改我点击的链接,而不会交换其他链接!我需要一个解决方案,它还可以从我之前单击的 NavItems 中删除所有事件链接。

 class NavItem extends Component{ 

constructor(props) {
super(props);

this.state = {
navigation: false,
};
}

toggleClass() {

this.setState({ navigation: !this.state.navigation });

};

render(){
return(
<li><Link
to={ this.props.href }
className={ this.state.navigation ? 'active' : null }
onClick={ () => this.toggleClass() }>{ this.props.text }</Link>
</li>
)
}

}

class Navigation extends Component{

render() {
return(
<nav>
<ul>
<NavItem href='galleries' text='Galleries' />
<NavItem href='archive' text='Archive' />
<NavItem href='news' text='News' />
<NavItem href='about' text='About' />
<NavItem href='contact' text='Contact' />
<NavItem href='map' text='Map' />
</ul>
</nav>
)
}

}

最佳答案

你需要提升你的状态并实现相同的逻辑

class NavItem extends Component{ 

toggleClass = () => {
this.props.toggleClass(this.props.text);
};

render(){
return(
<li><Link
to={ this.props.href }
className={ this.props.active ? 'active' : null }
onClick={this.toggleClass}>{ this.props.text }</Link>
</li>
)
}

}

class Navigation extends Component{


constructor(props) {
super(props);

this.state = {
navigation: '',
};
}
toggleClass = (items) => {
this.setState(prevState => ({ navigation: prevState.navigation === items? '': items }));
};
render() {

return(
<nav>
<ul>
<NavItem href='galleries' text='Galleries' toggleClass={this.toggleClass} active={this.state.navigation === 'Galleries'}/>
<NavItem href='archive' toggleClass={this.toggleClass} text='Archive' active={this.state.navigation === 'Archive'}/>
<NavItem href='news' toggleClass={this.toggleClass} text='News' active={this.state.navigation === 'News'}/>
<NavItem href='about' toggleClass={this.toggleClass} text='About' active={this.state.navigation === 'About'}/>
<NavItem href='contact' toggleClass={this.toggleClass} text='Contact' active={this.state.navigation === 'Contact'}/>
<NavItem href='map' toggleClass={this.toggleClass} text='Map' active={this.state.navigation === 'Map'} />
</ul>
</nav>
)
}

}

关于javascript - 在 React 中为 child 或其相关 sibling 切换事件类 onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48093578/

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