React实现随机颜色选择器的示例代码

  import { useMemo, useState } from "react";

  import { getRandomColor } from "@/utils/color";

  import classnames from "classnames";

  import { Check, Refresh } from "@icon-park/react";

  import { nanoid } from "nanoid";

  interface ColorSelectProps {

  defaultValue: string;

  value?: string;

  onChange?: (value: string) => void;

  }

  export default function ColorSelect(props: ColorSelectProps) {

  const { defaultValue, value, onChange } = props;

  // 用于重新生成颜色

  const [randomId, setRandomId] = useState("");

  const colors = useMemo(() => {

  // 随机生成6个颜色

  return new Array(6).fill(0).map(() => getRandomColor());

  }, [randomId]);

  const targetColors = useMemo(() => {

  // 过滤是否存在默认值的情况

  return [...colors, defaultValue || ""].filter(

  v => !!v && !["#"].includes(v),

  );

  }, [defaultValue, colors]);

  return (

  

  {targetColors.map(color => {

  console.log("color--->", color);

  return (

  

  key={color}

  data-color={color}

  onClick={() => onChange?.(color)}

  className={classnames(

  "h-8 w-8 cursor-pointer flex justify-center items-center",

  )}

  style={{ backgroundColor: color }}>

  {value === color && (

  

  )}

  

  );

  })}

  

  className="h-8 w-8 cursor-pointer flex justify-center items-center border border-solid border-color-BGBrown text-color-BGBrown text-P4-Regular"

  onClick={() => setRandomId(nanoid())}>

  

  

  

  );

  }