javascript 每个Map项顺风React的颜色变量变化

vbkedwbf  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(110)

我想,一旦我在列表中添加另一个项目的颜色为前一个项目不应该改变

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>
  );
};
fwzugrvs

fwzugrvs1#

你可以用两种方法解决这个问题

1. useRef
import { useRef } from "react";

const NoteItem = ({ note }) => {
  const { colors, randomColorFunction } = useContext(AppContext);
  const color = useRef(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.current}` }}
    >
      ...
    </div>
  );
};
2. useState
import { useState } from "react";

const NoteItem = ({ note }) => {
  const { colors, randomColorFunction } = useContext(AppContext);
  const [color] = useState(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}` }}
    >
      ...
    </div>
  );
};

如果你不想改变颜色,我认为useRef更合适。
请参见此处a live preview

相关问题