如何使用React动态添加和删除类?

问题描述 投票:0回答:3

我有一个链接列表。

我在点击上添加了一个名为“is-active”的课程。与此同时,我想删除所有现有的“is-active”,除了我点击的链接。可能只有一个元素具有“is-active”类,因为它将是“live”页面。 (使用bulma css)

这是我到目前为止尝试过的代码。它正在添加类但不删除它们。

    class Menu extends Component {

        constructor(props) {
            super(props);
            this.state = {addClass: false}
          };

          handleClick(e) {
            if(e.target.class === 'is-active'){
              e.target.className = '';
              console.log('remove')
            }else{
              e.target.className = 'is-active';
              console.log('add class')
            }
          }  

    render() {

                        <ul className="menu-list">
                        { this.props.getList.map(list =>
                             <Link onClick={this.handleClick.bind(this)} key={list.id} to="">{list.title}</Link>                    
                            )}
                        </ul>

    }

    }
export default SideMenu;

建议将非常感激。我现在只学习React大约一个星期了,到目前为止一直都很喜欢它。

干杯

javascript reactjs button classname
3个回答
3
投票

你必须自己避免触摸DOM,让React为你做。

您希望将信号保持在告诉您列表中的元素是否处于活动状态的状态,并使用该信号在渲染阶段设置类:

state = {
  activeId: null  // nothing selected by default, but this is up to you...
}

handleClick(event, id) {
  this.setState({ activeId: id })
}

render() {
  <ul className="menu-list">
  {
    this.props.getList.map(list =>
      <Link key={ list.id }
            className={ this.state.activeId === list.id && 'is-active' }
            onClick={ this.handleClick.bind(this, list.id) } 
            to="">
        { list.title }
      </Link>                    
    )
  }
  </ul>
}

这样,在每个render,你的id道具中每个项目的getList与你保持在你所在州的那个相比较,然后:

  1. 如果它是活动ID,则分配'is-active'类;
  2. 如果它不是活跃的,它会清除以前的className(如果它是'活跃的';

希望能帮助到你 :)


2
投票

如果您使用React直接避免DOM操作。你唯一要改变的应该是状态,让React处理DOM。

对于更改类名,我建议使用名为classnames的库(https://github.com/JedWatson/classnames)。它只会占用捆绑包大小的588个字节。

如果您不想使用第三方库,请使用JavaScript模板文字来执行此操作。

例:

<div className={ `list-item ${this.state.active ? "active" : ""}` }>...</div>

1
投票

如果您正在使用react-router来处理应用程序中的导航,则可以使用NavLink组件,该组件接受在网址匹配时添加类的道具。 <NavLink to="yourPath" activeClassName="is-active">Home<NavLink>

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