首页 > 解决方案 > 在 React 组件之间传递数据

问题描述

在我的反应页面中,我正在构建一个 html 表。表行是从子组件生成的,如下所示'ViewGRNTable'
到此页面为止运行良好
,我还想从子组件的每一行中获取一个值并将其添加到“this.state.GRNtotal”中。为此,我编写了一个回调函数“callbackRowSum”,它返回“rowsum”并将其添加到 this.state.GRNtotal

    ViewGRNCartTableRow(){
        return this.state.cartProducts.map(function(object,i){
            return <ViewGRNTable obj={object} key={i} callbackSum = {this.callbackRowSum} />;
        });
    }
    callbackRowSum = (rowsum) => {
        this.setState({GRNtotal: this.state.GRNtotal+rowsum})
    }

但它给出了一个错误
TypeError: Unable to get property 'callbackRowSum' of undefined or null reference
please help

标签: javascriptreactjs

解决方案


这是一个绑定问题,将您的功能更改为箭头功能

ViewGRNCartTableRow(){
  return this.state.cartProducts.map((object,i) => (
    <ViewGRNTable
      obj={object}
      key={i}
      callbackSum={this.callbackRowSum}
    />
  ));
}

这是因为您没有将this关键字绑定到传递给的函数map,您可以使用箭头函数轻松解决该问题,或者您可以像这样手动绑定函数

ViewGRNCartTableRow(){
  return this.state.cartProducts.map(function(object,i){
    return (
      <ViewGRNTable
        obj={object}
        key={i}
        callbackSum={this.callbackRowSum}
      />
    );
  }.bind(this));
}

推荐阅读