当我点击导航链接时,我可以成功切换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>
)
}
}
答案 0 :(得分:2)
您需要提升状态并实施与
相同的逻辑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>
)
}
}