reactjs addClass 和 removeClass 反应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49014937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:27:12  来源:igfitidea点击:

addClass and removeClass react

reactjs

提问by Sourabh Banka

I want to check that the target element contains a class or not. if not add the class and if yes then remove the class.

我想检查目标元素是否包含类。如果没有添加类,如果是,则删除类。

class Hello extends React.component{
  addActiveClass(e){
     if(e.target.classList.contains("active")){
         //I wanna to add active class to e.target
     }else{
         //I wanna to remove active class from e.target
         //I wanna to do something like e.target.classList.removeClass("atcive");
     }
  }

  render() {
       <div className="red green blue" onClick={this.addActiveClass}>Hello World</div>
       <div className="red green blue" onClick={this.addActiveClass}>Good Bye World</div>

  }
}

I wanna to add and remove class to only target element not the other elements.

我想添加和删除类只针对目标元素而不是其他元素。

回答by Shubham Khatri

You can make use of the state to store the active div and then conditionally add active class to it

您可以利用状态来存储活动 div,然后有条件地向其添加活动类

class Hello extends React.component{
  state = {
    active: ''
  }
  addActiveClass(e){
      const clicked = e.target.id
      if(this.state.active === clicked) { 
          this.setState({active: ''});
      } else {
          this.setState({active: clicked})
     }
  }

  render() {
     return (
   <div>
<div className={`red green blue ${this.state.active === "first"? 'active': ''}`} id="first" onClick={this.addActiveClass}>Hello World</div>
<div className={`red green blue ${this.state.active === "second"? 'active': ''}`} id="second" onClick={this.addActiveClass}>Good Bye World</div>
  </div>
     )
  }
}

回答by Yash Thakur

My answer is similar to others but I love this part what I do here:

我的回答与其他人相似,但我喜欢我在这里所做的这部分:

class ChildComp extends React.Component{
   super(props);
   this.state = {
      active: false
   }

   toggle(e){
      this.setState({active: !this.state.active});
   }

   render(){
     return(
        <div 
          className={classNames(
            "red green blue", 
            this.state.active ? "active" : "" 
          )}
          onClick={e => this.toggle(e)}
        >
          {this.props.text}
        </div>
     );
   }
}
class Hello extends React.Component{
   render(){
      return(
         <div>
            <ChildComp text="Hello World"/>
            <ChildComp text="GoodBye World"/>
         </div>
      );
   }
}