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

React-table实现仅首个含‘test’的行文字加粗问题求助

解决React-Table仅加粗首个含'test'文本行的问题

你之前的实现会把所有匹配行加粗,核心问题是没有在组件层面维护「是否已出现第一个匹配行」的状态——如果直接在makeCellBold里用局部变量,每次组件渲染都会重置这个变量,导致要么全加要么全不加。

正确的做法是先预处理数据,找到第一个包含'test'的行的唯一标识,再在单元格渲染时判断当前行是否为目标行:

修改后的完整实现代码

import { useMemo } from 'react';
import { Column } from 'react-table';

// 假设你的行数据类型定义
interface RowData {
  accessor1: any;
  accessor2: any;
  accessor3: any;
  DummyTestString: string;
  id?: string; // 假设每行有唯一id,无id可改用索引
}

const YourTableComponent = ({ data }: { data: RowData[] }) => {
  // 用useMemo缓存第一个匹配行的标识,仅在数据源变化时重新计算
  const firstMatchedRowId = useMemo(() => {
    const matchedRow = data.find(row => row.DummyTestString.includes('test'));
    return matchedRow?.id ?? null;
    // 若无id,改用索引:
    // return data.findIndex(row => row.DummyTestString.includes('test'));
  }, [data]);

  const makeCellBold = (value: {} | null | undefined, row: RowData) => {
    // 判断当前行是否为第一个匹配行
    const isFirstMatched = row.id === firstMatchedRowId;
    // 用索引的话替换为:row.index === firstMatchedRowId
    return <Typography fontWeight={isFirstMatched ? '500' : 'inherit'}>{value}</Typography>;
  };

  const columns: Column<RowData>[] = useMemo(() => [
    {
      Header: 'header1',
      accessor: 'accessor1',
      Cell: ({ value, row }) => makeCellBold(value, row.original),
    },
    {
      id: 'row',
      Header: 'header2',
      accessor: 'accessor2',
      Cell: ({ value, row }) => makeCellBold(value, row.original),
    },
    {
      id: 'row',
      Header: 'header3',
      accessor: 'accessor3',
      Cell: ({ value, row }) => makeCellBold(value, row.original),
    },
  ], [firstMatchedRowId]);

  return <Table columns={columns} data={data} />; // 渲染你的react-table组件
};

关键说明

  • 用useMemo缓存匹配行标识,避免每次渲染重复遍历数据源,提升性能
  • 优先使用行的唯一id判断,比索引更可靠(索引会因数据排序/过滤变化)
  • 禁止在单元格渲染函数内直接查找匹配行,否则会引发大量重复计算

内容的提问来源于stack exchange,提问作者newProgrammer.cpp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:15:40