reactjs - 从 React 表中获取单元格值
问题描述
我有一个看起来像这样的反应表。我希望能够单击每个单独的单元格并获取值。我知道你可以得到整行,但我只想要点击每个单独的单元格,这样我就可以将它保存为这样的状态
{
"Team": GB,
"MoneyLine": -120
}
{
"Team": GB,
"Spread": 1
}
{
"Team": GB,
"MoneyLine": -120,
"Spread": -1,
"Total": 48
}
我试过这个链接How to get cell value on React-Table?
但它没有提供太多解释。
每当单击行中的任何单元格,然后单击特定值时,我都需要获取团队名称。
这是代码
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()}
>
这是一个完整的工作 CodeSandbox: https ://codesandbox.io/s/fervent-shape-jr8tm?file=/src/App.js:1325-1489
推荐阅读
- git - Git rebase 冲突
- bash - 难以在 bash 中使用 readlink 混合变量和字符串来返回绝对路径
- javascript - 错误:无法解析 LoginPage 的所有参数:([object Object]、[object Object]、[object Object]、?)
- c++ - 我的代码,有时它说在抛出“std::bad_alloc”what() 的实例后调用终止:std::bad_alloc。然后有时它不会
- linux - 使用带有 FSELECT 的对话框的基本文件资源管理器:Bash 和循环?
- php - 在 null 上调用成员函数 attach()
- reactjs - Firebase Auth,在从反应客户端登录用户后,如何验证用户在我的其他 api 中是否合法?
- web-scraping - Jsoup 超时并且 cURL 仅适用于“--compressed”标头 - 如何在 Jsoup 中模拟此标头?
- python - 当我在 python 中运行我的刽子手游戏时出现此错误:_tkinter.TclError: invalid command name ".!canvas"
- mysql - Mysql如何将have()与min()结合起来