react useState中的单项更新



我有一个名为list的数组useState(单词列表(。列表中有4项,我想更新该列表的第二项(例如(。我正在使用地图功能来显示它们。这是代码(演示代码(-

const word = ['a','b','c','d']
const [list, setList]=useState([])
for(let I=0; I<4;I++) 
{setList(<span className='black'>word[I])</span>}

function colorChane(n){
How to change color of a 
word based on the number 
provided ??if I provide 2 
then the word with the 
index 2 should change to 
color.className should 
change like className= 'red'
How to update the className
Of list item.
}
list.map(w => {w})
colorChange(2)

试试这个

import { useState } from 'react'
export default function App() {
const words = ['Hi!', 'How', 'are', 'you']
const [selectedWordIndex, setSelectedWordIndex] = useState()
return (
<div>
<button
onClick={() => {
setSelectedWordIndex(2)
}}
>
Change color of second word
</button>

{words.map((word, index) => {
const isSelected = selectedWordIndex === index
const className = isSelected ? 'red' : 'black'
return (
<span key={word} className={className}>
{word}
</span>
)
})}
</div>
)
}

Ps。如果答案有帮助,请竖起大拇指:(

最新更新