React onClick add class to clicked element but remove from the others

后端 未结 2 1695
一向
一向 2021-01-26 11:57

so what i try to achieve here is very similar to what is done here Transition flex-grow of items in a flexbox

But what i wonder how this could be done with React say i h

相关标签:
2条回答
  • 2021-01-26 12:22

    const { useState, useEffect } = React;
    
    const App = () => {
      const [divs,] = useState(['blue', 'green', 'black']);
      const [selected, setSelected] = useState(null);
      
      const onClick = (id) => {
        setSelected(id);
      }
      
      return <div className="container">
        {divs.map(pr => <div key={pr} style={{background: pr}} className={`box ${pr === selected ? 'selected' : ''}`} onClick={() => onClick(pr)}></div>)}
      </div>
    }
    
    ReactDOM.render(
        <App />,
        document.getElementById('root')
      );
    .container {
      display: flex;
      height: 200px;
    }
    
    .box {
      flex: 1;
      cursor: pointer;
      transition: all .3s ease-in;
    }
    
    .selected {
      flex: 2;
    }
    <script src="https://unpkg.com/react/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
    <script src="https://unpkg.com/material-ui-lab-umd@4.0.0-alpha.32/material-ui-lab.development.js"></script>
    <div id="root"></div>

    0 讨论(0)
  • 2021-01-26 12:34

    You can set active index on click:

    // State
    this.state = {
      activeIndex: null
    };
    // event
    onElementClicked(e) {
      this.setState({ activeIndex: e.target.index })
    }
    // class to use
    className={this.index === this.state.activeIndex ? 'big-size' : ''}
    
    0 讨论(0)
提交回复
热议问题