You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Styled Components实现表格优先级文本颜色动态设置问题求助

解决优先级列文本颜色不生效的问题

问题根源分析

  1. 全局状态无法区分单个任务
    你用全局useState定义的highPriority会被所有单元格共享,只要有一个任务是high优先级,这个状态就会变为true,导致所有优先级列文本都变红,完全不符合“仅high优先级任务变红”的需求。而且循环中多次调用setHighPriority(true),React状态更新是批量的,最终只会保留最后一次的结果,逻辑完全错误。

  2. Styled Component的props传递错误
    使用Styled Component时,你错误地用props={highPriority}传递属性,正确的做法是直接给组件传递对应名称的props,比如highPriority={...}。


修复步骤

1. 删除全局highPriority状态

不需要这个全局状态,每个任务的优先级判断直接在渲染单个单元格时进行。

2. 简化Styled Component的颜色逻辑

你原来的代码写了两个color属性,后面的会覆盖前面的,直接简化为一个判断即可:

const Td = styled.td`
  height: 60px;
  vertical-align: middle;
  color: ${(props) => props.highPriority ? "#f32424" : "black"};

  &:first-child {
    width: 10%;
  }
  &:nth-child(2) {
    width: 10%;
  }
  &:nth-child(3) {
    width: 10%;
  }
  &:nth-child(4) {
    width: 10%;
  }
  &:nth-child(5) {
    width: 20%;
  }
  &:nth-child(6) {
    width: 40%;
  }
  &:nth-child(7) {
    width: 4%;
  }
  &:nth-child(8) {
    width: 3%;
  }
  &:last-child {
    width: 3%;
  }

  /* font-weight: ${(props) => (props.highPriority ? 600 : 400)}; */
`;

3. 修改Td组件的调用方式

渲染优先级列时,直接根据当前任务的priority值判断是否传递highPriority为true:

// 假设在任务列表的map循环中渲染
{allTasks.map(task => (
  <tr key={task.id}>
    {/* 其他列渲染代码 */}
    <Td highPriority={task.priority === "high"}>{task.priority}</Td>
    {/* 其他列渲染代码 */}
  </tr>
))}

4. 清理useEffect中的错误代码

删除循环内的setHighPriority(true),同时优化状态更新逻辑——不要在循环内多次调用setState,应该整理好所有数据后一次性设置:

useEffect(() => {
    const fetchTasks = async (id) => {
      const res = await fetch(`${taskFetchPath}/organization/${user.organization}`, {
        method: "GET",
        mode: "cors",
      });
      let data = await res.json();
      setAllTasks(data);
      console.log(data);

      let overdueTasks = [];
      let inProgressTasks = [];
      let completedTasks = [];

      for (const task of data) {
        const dueDate = new Date(task.due_date);
        const dueDateFormatted = format(dueDate, "MM/dd/yyyy");
        const today = Date.now();
        const todayFormatted = format(today, "MM/dd/yyyy");

        if (dueDateFormatted < todayFormatted && task.isComplete === "NO") {
          overdueTasks.push(task);
        } else if (dueDateFormatted >= todayFormatted && task.isComplete === "NO") {
          inProgressTasks.push(task);
        } else if (task.isComplete === "YES") {
          completedTasks.push(task);
        }
      }
      // 循环结束后一次性更新状态,减少重渲染次数
      setOverdueTasks(overdueTasks);
      setInProgressTasks(inProgressTasks);
      setCompletedTasks(completedTasks);
    };

    fetchTasks();
  }, [user.organization]);

内容的提问来源于stack exchange,提问作者David Wendt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 08:35:24