簡體   English   中英

如何使用 useState 突出顯示 antd 表中的一行?

[英]How can I highlight one row in antd table with useState?

所以我有一個坐標表,當我點擊一個特定的行時,它應該突出顯示,其他行應該是默認顏色。 現在它看起來像這樣:

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;

當我點擊一行時,所有行都會突出顯示,我怎么才能只顯示一行呢?

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

您可以設置活動記錄,並將其與rowClassName屬性的record參數 function 進行比較。如果它們相同,則將您的自定義 class 名稱設置為您單擊的這一行。

rowClassNamefunction(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;

antd版本:v5.0.5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM