我正在嘗試在反應中實作此功能:
默認狀態:所有串列項都是藍色的;
如果單擊一個特定專案:同一專案文本顏色變為紅色;
單擊任何其他專案時:最后一個專案的文本顏色恢復為藍色;
在我的代碼中,專案文本顏色保持紅色,即使單擊其他專案也是如此。
我在這里搜索,似乎我應該使用 useRef 和 item.id 但我被困在如何實作這個特定功能上。
謝謝
應用程式.js
import { useState } from 'react'
import Item from './components/Item'
function App() {
const [items, setItems] = useState([
{
id: 1,
name: 'Item 1',
},
{
id: 2,
name: 'Item 2',
},
])
return (
<>
{items.map((item) => (
<Item key={item.id} id={item.id} name={item.name} />
))}
</>
)
}
export default App
專案.jsx
import { useState } from 'react'
function Item({ id, name }) {
const [clicked, setClicked] = useState(false)
const handleClick = () => {
setClicked(!clicked)
}
return (
<>
<button
onClick={handleClick}
style={{ color: clicked ? 'red' : 'blue' }}
key={id}
>
{name}
</button>
</>
)
}
export default Item
uj5u.com熱心網友回復:
您需要在父組件中維護選定的 id,并根據選擇我們可以更改按鈕文本的顏色。
應用程式.jsx
import { useState } from 'react'
import Item from './components/Item'
function App() {
const [items, setItems] = useState([
{
id: 1,
name: 'Item 1',
},
{
id: 2,
name: 'Item 2',
},
])
const [selectedId,setSelectedId] = useState(null)
return (
<>
{items.map((item) => (
<Item key={item.id} id={item.id} name={item.name} handleClick={() => setSelectedId(item.id)} clicked={selectedId === item.id} />
))}
</>
)
}
export default App
專案.jsx
function Item({ id, name, clicked, handleClick }) {
return (
<button
onClick={handleClick}
style={{ color: clicked ? 'red' : 'blue' }}
key={id}
>
{name}
</button>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/469305.html
標籤:javascript 反应 反应钩子 使用状态