【问题标题】:Error in passing an argument to a map callback function in React将参数传递给 React 中的映射回调函数时出错
【发布时间】:2025-12-21 03:10:12
【问题描述】:

我有一个 React 组件,它使用 map 函数来显示一些数据。问题是当我将回调函数传递给并使用 classes 属性时,我收到一个错误提示

未捕获的引用错误:未定义类

这是我的代码。请注意,类是定义的。如何在我拥有的回调函数上正确访问它?

class ProvidersPage extends React.Component {
  constructor(props, context) {
    super(props, context);
  }

  providerRow(provider, index) {
    return <TableRow className={classes.row} key={index}>
      <CustomTableCell component="th" scope="row">
        {provider.name}
      </CustomTableCell>
      <CustomTableCell>{provider.type}</CustomTableCell>
      <CustomTableCell>{provider.pointOfContact}</CustomTableCell>
      <CustomTableCell>{provider.telephoneNumber}</CustomTableCell>
      <CustomTableCell>{provider.licenseNumber}</CustomTableCell>
      <CustomTableCell>{provider.licenseSource}</CustomTableCell>
      <CustomTableCell>
        <IconButton>
          <MoreHorizIcon />
        </IconButton>
      </CustomTableCell>
    </TableRow>
  }

  render() {
    const { classes } = this.props;

    return (
      <div>
        <Paper className={classes.root} elevation={4}>
          <Table className={classes.table}>
            <TableHead>
              <TableRow>
                <CustomTableCell>Name</CustomTableCell>
                <CustomTableCell>Type</CustomTableCell>
                <CustomTableCell>Point of Contact</CustomTableCell>
                <CustomTableCell>Telephone Number</CustomTableCell>
                <CustomTableCell>License Number</CustomTableCell>
                <CustomTableCell>License Source</CustomTableCell>
                <CustomTableCell>Actions</CustomTableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {this.props.providers.map(this.providerRow)}
            </TableBody>            
          </Table>
        </Paper>
      </div>
    );
  }
}

【问题讨论】:

  • providerRow 上的更改:className={this.props.classes.row}
  • @nirsky 如果他/她这样做,他/她也需要map(this.providerRow, this)
  • 你好@nirsky,这样做了,但现在显示的错误是 Uncaught TypeError: Cannot read property 'props' of undefined。
  • 添加到你的构造函数:this.providerRow = this.providerRow.bind(this)
  • @ASDFGerte 谢谢。那行得通。有没有什么文章可以让人们熟悉这类问题中的 this 关键字?

标签: javascript reactjs material-ui


【解决方案1】:

您必须将类变量传递给回调函数才能将其作为参数传递。

this.props.providers.map(this.providerRow.bind(this, classes))

providerRow 函数原型是:

providerRow(classes, provider, index)

或者你的 props 中也有类,所以你必须在 providerRow 函数的开头编写这一行:

const { classes } = this.props;

【讨论】: