从 React 获取单元格值 table

Get cell value from React table

我的反应 table 看起来像这样。 我希望能够单击每个单独的单元格并获取值。我知道你可以获得整行,但我只想要每个单独的单元格,当它被点击时,我可以将它保存在这样的状态

{
    "Team": GB,
    "MoneyLine": -120
}
{
    "Team": GB,
    "Spread": 1
}
{
    "Team": GB,
    "MoneyLine": -120,
    "Spread": -1,
    "Total": 48
}

我试过了link

但它没有提供太多解释。

我需要在单击行中的任何单元格时获取团队名称,然后获取单击的特定值。

这是代码

import React, { useState } from 'react'
import styled from 'styled-components'
import { useTable } from 'react-table'
import data from '../Data/data.json'

const Styles = styled.div`
  padding: 1rem;

  table {
    border-spacing: 0;
    border: 1px solid black;

    tr {
      :last-child {
        td {
          border-bottom: 0;
        }
      }
    }

    th,
    td {
      margin: 0;
      padding: 0.5rem;
      border-bottom: 1px solid black;
      border-right: 1px solid black;

      :last-child {
        border-right: 0;
      }
    }
  }
`

function Table({ columns, data }) {

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = useTable({
    columns,
    data,
  })

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()} >{column.render('Header')}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, _) => {
          prepareRow(row)
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td {...cell.getCellProps()} >{cell.render('Cell')}</td>
              })}
            </tr>
          )
        })}
      </tbody>
    </table>
  )
}

export default function PicksTable(){
    const [team, setTeam] = useState('');
    const [moneyLine, setMoneyLine] = useState('');
    const [spread, setSpread] = useState('');
    const [total, setTotal] = useState('');

    const columns = React.useMemo(
        () => [
        {
            Header: 'Teams',
            columns: [
            {
                Header: 'Team',
                accessor: 'team',
            },
            ],
        },
        {
            Header: 'Betting Info',
            columns: [
            {
                Header: 'Money Line',
                accessor: 'moneyLine',
            },
            {
                Header: 'Spread',
                accessor: 'spread',
            },
            {
                Header: 'Total',
                accessor: 'total',
            },
            ],
        },
    ],
    []
  )

  return (
    <Styles>
      <Table columns={columns} data={data} />
    </Styles>
  )
}

您需要将 onClick 添加到 <td>(值在行和单元格中):

  <td
    onClick={() => console.info(row.values.team, cell.value)}
    {...cell.getCellProps()}
  >

这是一个完整的工作代码沙盒: https://codesandbox.io/s/fervent-shape-jr8tm?file=/src/App.js:1325-1489