首页 > 解决方案 > 在 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'
    })

有什么想法我在这里缺少什么吗?

标签: javascriptreactjscallbackreact-props

解决方案


我认为您需要在像这样将回调作为道具传递时省略箭头函数

test={this.test}


推荐阅读