如何使用 Material UI 处理简单表格中一行的点击

Rub*_*ins 3 onclick reactjs material-ui

我正在使用 ui 材料的 DenseTable 组件,我希望能够从单击的行中获取所有数据,如果有人知道这将是一个很大的帮助

以下是我正在使用的组件的源代码:

import * as React from 'react';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';

function createData(name, calories, fat, carbs, protein) {
  return { name, calories, fat, carbs, protein };
}

const rows = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

export default function DenseTable() {
  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 650 }} size="small" aria-label="a dense table">
        <TableHead>
          <TableRow>
            <TableCell>Dessert (100g serving)</TableCell>
            <TableCell align="right">Calories</TableCell>
            <TableCell align="right">Fat&nbsp;(g)</TableCell>
            <TableCell align="right">Carbs&nbsp;(g)</TableCell>
            <TableCell align="right">Protein&nbsp;(g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <TableRow
              key={row.name}
              sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
            >
              <TableCell component="th" scope="row">
                {row.name}
              </TableCell>
              <TableCell align="right">{row.calories}</TableCell>
              <TableCell align="right">{row.fat}</TableCell>
              <TableCell align="right">{row.carbs}</TableCell>
              <TableCell align="right">{row.protein}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

Run Code Online (Sandbox Code Playgroud)

我知道用户界面材料有几个与此操作相关的组件,但它们非常复杂,我想要一个简单的表格

Jun*_*yad 8

您可以在单击该行时添加onClick处理程序,将行数据存储在状态变量或任何 UX 中TableRow

const [selectedRow, setSelectedRow] = React.useState({});

<TableRow
  onClick={() => setSelectedRow(row)}
  key={row.name}
  sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
>
Run Code Online (Sandbox Code Playgroud)

完整的代码如下所示

const [selectedRow, setSelectedRow] = React.useState({});

<TableRow
  onClick={() => setSelectedRow(row)}
  key={row.name}
  sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
>
Run Code Online (Sandbox Code Playgroud)