【问题标题】:How can I highlight one row in antd table with useState?如何使用 useState 突出显示 antd 表中的一行?
【发布时间】:2023-01-17 17:07:58
【问题描述】:

所以我有一个坐标表,当我点击一个特定的行时,它应该突出显示,其他行应该是默认颜色。 现在它看起来像这样:

const TableComponent = () => {
  const [active, setActive] = useState(false);

  useEffect(() => {
    console.log(active);
  }, [active]);

  return (
    <Table
      dataSource={dataSource}
      columns={columns}
      rowClassName={active ? "green" : null}
      onRow={(record, rowIndex) => {
        return {
          onClick: (event) => {
            setActive(true);
          }, // click row
        };
      }}
    />
  );
};

export default TableComponent;

当我点击一行时,所有行都会突出显示,我怎么才能只显示一行呢?

【问题讨论】:

    标签: reactjs react-hooks antd


    【解决方案1】:
    const App = () => {
      const [activeIndex, setActiveIndex] = useState()
      return (
        <Table
          columns={columns}
          dataSource={data}
          rowClassName={(record, index) => (index === activeIndex ? 'green' : null)}
          onRow={(record, rowIndex) => {
            return {
              onClick: (event) => {
                setActiveIndex(rowIndex)
              }, // click row
            }
          }}
        />
      )
    }
    

    【讨论】:

      【解决方案2】:

      您可以设置活动记录,并将其与 rowClassName prop 函数的 record 参数进行比较。如果它们相同,则将您的自定义类名称设置为您单击的这一行。

      rowClassName prop 有function(record, index): string 签名,你应该总是返回字符串而不是null

      type ID = string | number;
      
      const TableComponent = () => {
        const [activeRecord, setActiveRecord] = useState<{ id: ID }>();
      
        console.log(activeRecord);
      
        return (
          <Table
            dataSource={dataSource}
            columns={columns}
            rowClassName={(record) =>  record.id === activeRecord?.id ? "green" : ''}
            onRow={(record) => {
              return {
                onClick: () => {
                  setActiveRecord(record);
                }, 
              };
            }}
          />
        );
      };
      
      export default TableComponent;
      

      【讨论】:

        猜你喜欢
        • 2010-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多