我有一個名為 list 的陣列 useState(單詞串列)。串列中有 4 個專案,我想更新該串列的第二個專案(例如)。我正在使用 map 函式來顯示它們。這是代碼(演示代碼) -
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)
uj5u.com熱心網友回復:
嘗試這個
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>
)
}
附言。如果回答對你有幫助,請點贊:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432124.html
標籤:javascript 反应 使用状态
下一篇:設定單選按鈕之間的狀態
