在React中切换子项或其相关兄弟单元的活动类

问题描述 投票:2回答:1

当我单击导航链接时,我可以成功切换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>
        )
    }

}
javascript reactjs
1个回答
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>
        )
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.