javascript - 在 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
解决方案
这是一个绑定问题,将您的功能更改为箭头功能
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));
}
推荐阅读
- ethereum - 错误 HH12:尝试使用不支持的非本地安装的 Hardhat。请使用 npm 或 Yarn 在本地安装 Hardhat,然后重试
- javascript - 有没有办法在一个关卡中合并多个图块 - Kaboom JS
- c# - 带有实体框架和 SQL Server 数据库的 ASP.NET MVC - 图像未显示在视图中......错误显示“无法将“字节”转换为“字符串”
- mysql - 在子查询中使用父 SQL 列
- node.js - Node.js fast-glob EACCES:权限被拒绝
- c - 如何在C中找到数组中输入元素的值
- flutter - 使用 post 请求将图片发送到服务器 api [FLUTTER]
- javascript - 如何让多个按钮成为焦点?HTML/CSS/JS
- c++ - C ++中的数字总和
- docker - 为什么 https 不适用于我在 docker 中托管的网站?