在 React JS 中单击第一行时如何获取 Id?

How do I get the Id when clicked on the first row in React JS?

我是 React 的新手,我正在按照教程构建一个 react-table,但我想更进一步,看看我是否可以让第一行或单元格可点击并获得该单元格的 ID。但是,我无法做到这一点。我不确定这个问题是否已经得到解答,但我找不到任何答案。

App.js

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    getData();
  }, []);
  const getData = async () => {
    const result = await axios
      .get("https://api.tvmaze.com/search/shows?q=spider")
      .then((response) => {
        setData(response.data);
        console.log(response.data);
      });

    return result;
  };

  const columns = useMemo(
    () => [
      {
        Header: "Tv Show",
        columns: [
        
          {
            Header: "Name",
            accessor: "show.name",
          },
          {
            Header: "Type",
            accessor: "show.type",
          },
        ],
      },

Table.js

 return (
          <tr {...row.getRowProps()} data={columns} onClick={checkButton}>

这是 API

的一部分
[{"score":20.77334,"show":{"id":4107,"url":"https://www.tvmaze.com/shows/4107/spider-man","name":"Spider-Man","type":"Animation","language":"English","genres":["Action","Adventure","Children"],"status":"Ended","runtime":30,"premiered":"1967-09-09","officialSite":null,

Tbh 我不知道 checkButton 函数中应该有什么,我有很多东西可以获取数据,但我做不到。非常感谢您的指导。谢谢!

您在 table 行上使用 onClick 是正确的。只需添加一个简单的函数来检查行索引:

const logDataIfFirstRowClicked = (row) => {
    if (row.index === 0) {
      console.log("FIRST ROW CLICKED");
      console.log(row); // returns row object: {id: "0", original: Object, index: 0, depth: 0, cells: Array(2)…} 
      console.log(row.original) // returns the data from the row ex: {actor: "Johnny Depp", movie: "Pirates of the Carribean 1"}
    }
  };

并将其传递给您的 table 行:

rows.map(row => ({
  <tr {...row.getRowProps()} onClick={() => logDataIfFirstRowClicked(row)}>
}))

您还可以使用 Column 定义中的 Cell 渲染方法来添加点击。如果您只希望每行的第一个单元格在点击时 return 它的值,它可能看起来像这样:

const columns = useMemo(
    () => [
      {
        Header: "Tv Show",
        columns: [
        
          {
            Header: "Name",
            accessor: "show.name",
          },
          {
            Header: "Type",
            accessor: "show.type",
          },
        ],
        // Set the custom cell render here:
        Cell: (cell) => (
          <button
            // add on click to your custom cell
            onClick={() => console.log(cell.value)}
          >
            {" "}
            {cell.value}{" "}
          </button>
        )
      },
    ]

看看这个 DEMO and this example on React-Table's GitHub

Row Properties section of React-Table docs