簡體   English   中英

Go 在表格內單擊時指向鏈接。帶有 onClick 的行

[英]Go to a link when clicked inside a Table.Row with onClick

我有一個表,我希望每一都是可點擊的,當你點擊它到 go 到那個鏈接(每行不同)。

<Table.Body>
  {rows.map((row, rowIndex) => (
    <Table.Row
      key={idList && idList[rowIndex]}
      onClick={() => {
        <Link
          to={
            entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
          }
        />;
      }}>
      ...
    </Table.Row>
  ))}
</Table.Body>

所以我像上面那樣做了,添加了一個組件但不起作用。 它說:

預期分配或 function 調用,而是看到一個表達式 no-unused-expressions

我正在使用Semantic UI中的Table / Table.Rowreact-router-dom中的Link 我無法更改Table ,但Link組件不是強制性的。 無論如何,如果它可以在單擊時重定向到該鏈接,那就太好了。

有什么辦法嗎?

一種方法是使用歷史從組件導航。 要獲取歷史 object,您需要使用可從react-router:5.1.0獲得的useHistory()掛鈎,或者如果您使用的是舊版本的 react-router

  1. 你將不得不添加一個方法來做到這一點:

功能性

const onNavigate = (entityName, idList) => () => {
  entityName && history.push( && `/${entityName}/${idList[rows.indexOf(row)]}`) // change accordingly 
}

Class

onNavigate = (entityName, idList) {
  return function () {
    return entityName && this.props.history.push( && `/${entityName}/${idList[rows.indexOf(row)]}`) // change accordingly 
  }
}

此方法返回 function 引用,因此onCLick道具不會在渲染時觸發它,並且some_props將在內部function中可見

  1. 您將方法傳遞給onClick方法:
<Table.Body>
  {rows.map((row, rowIndex) => (
    <Table.Row
      key={idList && idList[rowIndex]}
      onClick={onNavigate(enitityName, idList)}
    >
      ...
    </Table.Row>
  ))}
</Table.Body>

這樣,點擊處理程序將收到 function 引用,並應導航到相應的 url

使用react-router鏈接到 react 應用程序內部,您可以使用useHistory掛鈎並推送新路徑。

import { useHistory } from "react-router-dom";

function Component() {
  let history = useHistory();

  return (
    <Table.Body>
      {rows.map((row, rowIndex) => (
        <Table.Row
          key={idList && idList[rowIndex]}
          onClick={() =>
            history.push(
              entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
            )
          }
        >
          ...
        </Table.Row>
      ))}
    </Table.Body>
  );
}


暫無
暫無

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

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