在React中将参数传递给映射回调函数时出错

时间:2018-06-10 15:29:46

标签: javascript reactjs material-ui

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

未捕获的ReferenceError:未定义类

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

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>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

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

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

providerRow函数原型将是:

providerRow(classes, provider, index)

或者你的道具也有类,所以你必须把这一行写成providerRow函数的开头:

const { classes } = this.props;