我试图在单击的li元素上添加一些具有某些样式的简单类。第一个li元素可以正常工作,但另一个li元素需要双击才能应用该类(样式)。
请告诉我为什么会发生这种现象。

App.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state={
    clicked: false,
    index: 0,
    arr: ['a','b','c','d','e','f','g','h']
  }

  handleClick = (i) => {

    this.setState({
      clicked: !this.state.clicked,
      index: i
    });

  }
  render() {
    console.log(this.state.index);
    return (
      <div className='App'>
         <ul>
           {
             this.state.arr.map((el, i) => (
             <li key={i} className={(this.state.clicked && this.state.index === i) ? 'clicked':''}
                  onClick={() => this.handleClick(i)}>{el}</li>
             ))
           }
         </ul>
      </div>
    )
  }
}
export default App;


App.css

.App {
  text-align: center;
  width: 60vw;
  margin: 50px auto;
  border: 1px solid grey;
}

ul{
  list-style: none;
}

li{
  padding: 4px 7px;
  border: 1px solid grey;
  margin-bottom: 15px;
  text-align: left;
  width: 50%;
  cursor: pointer;
}

.clicked{
  background: #000;
  color: white;
}


CSS中单击的类是我以编程方式应用的内容。
我在这里想念什么?

最佳答案

更新:

刚刚意识到我们每次点击都会重新分配clicked。第一次单击后必须始终为true。



class App extends React.Component {
  state={
    clicked: false,
    index: 0,
    arr: ['a','b','c','d','e','f','g','h']
  }

  handleClick = (i) => {
    this.setState(state => ({
      clicked: true,
      index: i
    }));
  }

  render() {
    const shouldAddClassName = this.state.clicked === true;
    const currentIndex = this.state.index;
    console.log('currentIndex', currentIndex);
    return (
      <div className='App'>
         <ul>
           {
             this.state.arr.map((el, i) => (
             <li key={i} className={(shouldAddClassName && currentIndex === i) ? 'clicked': ''}
                  onClick={() => this.handleClick(i)}>{el}</li>
             ))
           }
         </ul>
      </div>
    )
  }
}

ReactDOM.render(<App /> , document.querySelector('#app'));

.App {
  text-align: center;
  width: 60vw;
  margin: 50px auto;
  border: 1px solid grey;
}

ul {
  list-style: none;
}

li {
  padding: 4px 7px;
  border: 1px solid grey;
  margin-bottom: 15px;
  text-align: left;
  width: 50%;
  cursor: pointer;
}

.clicked {
  background: #000;
  color: white;
}

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="app"></div>

09-07 21:18