我希望一旦我在清單中新增另一個項(xiàng)目,前一個項(xiàng)目的顏色就不應(yīng)更改
const NoteItem = ({ note }) => { const { colors, randomColorFunction } = useContext(AppContext); const color = randomColorFunction(colors); return ( <div className={`flex flex-col min-h-28 py-6 justify-between px-3 rounded-md whitespace-pre-wrap break-words`} style={{ backgroundColor: `${color}` }} > <span className="font-bold text-3xl">{note.title}</span> <span>{note.content}</span> <small className="text=xl">{note.date}</small> </div> ); };
你可以用兩種方式解決這個問題
import { useRef } from "react"; const NoteItem = ({ note }) => { const { colors, randomColorFunction } = useContext(AppContext); const color = useRef(randomColorFunction(colors)); return (...); };
import { useState } from "react"; const NoteItem = ({ note }) => { const { colors, randomColorFunction } = useContext(AppContext); const [color] = useState(randomColorFunction(colors)); return (...); };
如果您不想更改顏色,我認(rèn)為 useRef
更合適。
請參閱此處即時預(yù)覽