gpt4 book ai didi

javascript - ReactJs——在 li 元素的点击事件上,类不会立即添加

转载 作者:行者123 更新时间:2023-11-30 10:58:16 25 4
gpt4 key购买 nike

我正在尝试在单击的 li 元素上添加一些带有一些样式的简单类。第一个 li 元素完美运行,但另一个 li 元素需要双击才能应用该类(样式)。请告诉我为什么会发生这种行为。

应用程序.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;

应用.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。第一次点击后必须始终为真。

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>

关于javascript - ReactJs——在 li 元素的点击事件上,类不会立即添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59121726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com