javascript - 在 React 中将函数作为道具传递给子组件会引发错误
问题描述
在将回调作为道具传递给 React 中的子组件时,是否有任何特定的指导方针?
在某些时候,我在 app.js 中的代码如下所示:
test() {
}
render(){
return (
<div className="App">
<MiniDrawer handleProductChange={this.handleProductChange.bind(this)} product={{icon:'', name:'Magnifier', height:'20px'}}/>
<div className='inrow'>
<PowerbiEmbedded
id={this.state.ReportId}
embedUrl={"https://app.powerbi.com/reportEmbed?reportId="+this.state.ReportId+"&groupId="+this.state.workspaceId}
accessToken={this.state.accesstoken}
filterPaneEnabled={true}
navContentPaneEnabled={true}
bookmarksPaneEnabled={true}
test={() => this.test}
//pageName={`${YOUR_PAGE_ID}`}
//embedType={`Report`}
tokenType={0}
width='100%'
height='1000px'
/>
</div>
</div>
);}
MiniDrawer 组件不会发出任何与 handleProductChange 回调有关的问题。虽然我试图传递给 PowerBiEmbedded 组件的简单回调失败并出现错误:
DataCloneError:无法在“Window”上执行“postMessage”:() => this.test 无法克隆。我设法提取了问题的根源。子组件内部有一个函数使用带有 Object.assign 的道具。如果我注释掉这个函数错误就会消失。我能做些什么呢?
updateState (props) {
const nextState = Object.assign({}, this.state, props, {
pageName: this.props.pageName,
settings: {
/* panes:{
bookmarks: {visible: this.props.bookmarkPaneEnabled},
filters: {visible: this.props.filterPaneEnabled},
pageNavigation: {visible: this.props.navContentPaneEnabled}
},*/
filterPaneEnabled: this.props.filterPaneEnabled,
navContentPaneEnabled: this.props.navContentPaneEnabled,
bookmarkPaneEnabled: this.props.bookmarkPaneEnabled,
layoutType: this.props.mobile ? pbi.models.LayoutType.MobilePortrait : undefined
},
type: this.props.embedType ? this.props.embedType : 'report'
})
有什么想法我在这里缺少什么吗?
解决方案
我认为您需要在像这样将回调作为道具传递时省略箭头函数
test={this.test}
推荐阅读
- java - Java静态成员初始化
- jekyll - jekyll-seo-tag 在 Github 页面中不起作用
- python - 用 pandas 索引一个无限系列
- r - 使用 igraph 消除 clique 集群
- javascript - 如何在 WebGL 画布上渲染 2d 画布?
- arangodb - ArangoDB-我可以使用 foxx 进行审计服务来记录所有更改吗
- r - h2o.distance 和 dist 函数之间的差异
- spyder - Spyder 不处理相对进口
- python - 想要开始/暂停视频时,我应该如何正确使用 cv2.waitKey?
- sdl-2 - SDL2 - 结合前后缓冲区?