gpt4 book ai didi

reactjs - Material UI React Table onCellClick

转载 作者:行者123 更新时间:2023-12-03 14:31:28 26 4
gpt4 key购买 nike

我正在尝试在 Material UI 表上实现一个简单的 onCellClick 监听器。

在它的早期版本中,表范围onCellClick中的函数用于给出单击时的行号和列号,如图here

当前此功能放置时 -

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const styles = {
}
let id = 0;
function createData(name, calories, fat, carbs, protein) {
id += 1;
return { id, 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),
];

function SimpleTable(props) {
const { classes } = props;

return (
<Paper className={classes.root}>
<Table className={classes.table}
onCellClick={(rowNumber,
columnId) =>
console.log(rowNumber,columnId)}>
<TableHead>
<TableRow>
<TableCell>Dessert (100g serving)</TableCell>
<TableCell numeric>Calories</TableCell>
<TableCell numeric>Fat (g)</TableCell>
<TableCell numeric>Carbs (g)</TableCell>
<TableCell numeric>Protein (g)</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map(row => {
return (
<TableRow key={row.id}>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell numeric>{row.calories}</TableCell>
<TableCell numeric>{row.fat}</TableCell>
<TableCell numeric>{row.carbs}</TableCell>
<TableCell numeric>{row.protein}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Paper>
);
}


export default withStyles(styles)(SimpleTable);

它会抛出错误未知事件处理程序属性onCellClick。它将被忽略。这是预期的,因为与以前的版本不同,表 source code 中没有传递 onCellClick 函数。 .

现在如何在 Material-UI 中实现 onCellClick 功能?

任何帮助将不胜感激。

最佳答案

单元格可以是 thtd 元素 ( see the source code ) 或通过 component 属性传递的自定义元素。

其中每一个都将支持 onClick property .

所以你需要这样的东西:

handleClick = (id, column) => {
return (event) => {
console.log(`You clicked on row with id ${id}, in column ${column}.`);
}
}

render() {
return (
// ...
{this.state.rows.map((row) => (
<TableRow key={row.id}>
<TableCell onClick={this.handleClick(row.id, "calories")}>
{row.calories}
</TableCell>
// ...
<TableCell onClick={this.handleClick(row.id, "protein")}>
{row.protein}
</TableCell>
</TableRow>
)}
// ...
);
}

关于reactjs - Material UI React Table onCellClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51858496/

26 4 0