每个映射项目的颜色变量发生变化顺风反应
P粉982009874
P粉982009874 2024-04-04 00:13:35
[React讨论组]

我希望一旦我在列表中添加另一个项目,前一个项目的颜色就不应更改

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

P粉982009874
P粉982009874

全部回复(1)
P粉237125700

你可以通过两种方式解决这个问题

1。使用引用

import { useRef } from "react";

const NoteItem = ({ note }) => {
  const { colors, randomColorFunction } = useContext(AppContext);
  const color = useRef(randomColorFunction(colors));

  return (
    
...
); };

2.使用状态

import { useState } from "react";

const NoteItem = ({ note }) => {
  const { colors, randomColorFunction } = useContext(AppContext);
  const [color] = useState(randomColorFunction(colors));

  return (
    
...
); };

如果您不想更改颜色,我认为 useRef 更合适。

请参阅此处实时预览

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号