简体   繁体   English

如何使用 React 在点击时动态添加和删除类?

[英]How to dynamically add and remove class on click with React?

I have a list of links.我有一个链接列表。

I'm adding a class on click, called "is-active".我正在添加一个名为“is-active”的点击类。 At the same time, I would like to remove all the existing "is-active"s except for on the link I clicked on.同时,我想删除所有现有的“is-active”,除了我点击的链接。 There may only be one element with the class "is-active" as that will 'live' page.可能只有一个具有“is-active”类的元素,因为它会“活动”页面。 (Using bulma css) (使用 bulma css)

Here's the code I've tried so far.这是我迄今为止尝试过的代码。 It's adding classes but not removing them.它正在添加类,但不会删除它们。

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;

Advice would be sooo much appreciated.建议将不胜感激。

You must avoid touching the DOM by yourself, let's React do it for you.你必须避免自己接触 DOM,让 React 为你做。

You want to keep a signal in the state that tell's you whether an element in the list is active or not, and use that signal to set a class or not in your rendering phase:您希望保持一个信号处于状态,告诉您列表中的元素是否处于活动状态,并在渲染阶段使用该信号设置类:

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>
}

This way, at each render , the id of each item in your getList prop is compared to the one you keep in your state, then:这样,在每次render ,将getList道具中每个项目的id与您保持在状态中的项目进行比较,然后:

  1. if it's the active id, it assign the 'is-active' class;如果它是活动 id,则分配 'is-active' 类;
  2. if it's not the active one, it clears the previous className (in case it was 'is-active';如果它不是活动的,则清除前一个className (如果它是“活动的”;

Hope it helps :)希望能帮助到你 :)

If you are using React avoid DOM manipulation directly .如果您使用 React,请避免直接操作 DOM The only thing you are changing should be state, let React deal with DOM.你唯一改变的应该是状态,让 React 处理 DOM。

For changing class names I would recommend library called classnames ( https://github.com/JedWatson/classnames ).对于更改类名,我会推荐名为 classnames ( https://github.com/JedWatson/classnames ) 的库。 It will only occupy 588 bytes in your bundle size.它只会占用 588 字节的包大小。

If you don't want to use third party library then use JavaScript's template literals to do this.如果您不想使用第三方库,请使用 JavaScript 的模板文字来执行此操作。

Example:例子:

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

If your are using react-router for handling navigation in your app you can use the <NavLink> component that accepts a prop for adding a class when the url matches.如果您使用 react-router 在您的应用程序中处理导航,您可以使用<NavLink>组件,该组件接受一个 prop,以便在 url 匹配时添加一个类。

<NavLink to="/yourPath" activeClassName="is-active">Home<NavLink>

To use NavLink in your project, you must import it要在您的项目中使用 NavLink,您必须导入它

import { NavLink, Route } from 'react-router-dom'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM