REACT - toggle class onclick

后端 未结 14 1986
长情又很酷
长情又很酷 2020-11-27 11:40

I am trying to figure out how to toggle an active class onClick to change CSS properties.

I have taken many approaches, and read many SO answers. Using

14条回答
  •  广开言路
    2020-11-27 12:05

    Well, your addActiveClass needs to know what was clicked. Something like this could work (notice that I've added the information which divs are active as a state array, and that onClick now passes the information what was clicked as a parameter after which the state is accordingly updated - there are certainly smarter ways to do it, but you get the idea).

    class Test extends Component(){
    
      constructor(props) {
        super(props);
        this.state = {activeClasses: [false, false, false]};
        this.addActiveClass= this.addActiveClass.bind(this);
      }
    
      addActiveClass(index) {
        const activeClasses = [...this.state.activeClasses.slice(0, index), !this.state.activeClasses[index], this.state.activeClasses.slice(index + 1)].flat();
        this.setState({activeClasses});
      }
    
      render() {
        const activeClasses = this.state.activeClasses.slice();
        return (
          
    this.addActiveClass(0)}>

    0

    this.addActiveClass(1)}>

    1

    this.addActiveClass(2)}>

    2

    ); } }

提交回复
热议问题