addClass和removeClass做出反应

时间:2018-02-27 17:50:34

标签: reactjs

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

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>

  }
}

我想将class添加到目标元素而不是其他元素。

2 个答案:

答案 0 :(得分:2)

您可以使用状态来存储活动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>
     )
  }
}

答案 1 :(得分:2)

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

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