简体   繁体   English

将 function 作为道具传递给 React 中的子组件会引发错误

[英]passing function as a prop to child component in React throws error

Are there any specific guidelines when passing callbacks as props to child components in React?在将回调作为道具传递给 React 中的子组件时,是否有任何特定的指导方针?

At some point my code ina app.js looks the following:在某些时候,我在 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>
    
  );}

The MiniDrawer component does not signal any issues with handleProductChange callback. MiniDrawer 组件不会发出任何与 handleProductChange 回调有关的问题。 While simple callback which I am trying to pass to PowerBiEmbedded component fails with error:虽然我试图传递给 PowerBiEmbedded 组件的简单回调失败并出现错误:

DataCloneError: Failed to execute 'postMessage' on 'Window': () => this.test could not be cloned. DataCloneError:无法在“Window”上执行“postMessage”:() => this.test 无法克隆。 I managed to extract the source of the problem.我设法提取了问题的根源。 There is a function inside the child component using props with Object.assign.子组件内部有一个 function 使用带有 Object.assign 的道具。 If i comment out this function error disappears.如果我注释掉这个 function 错误就会消失。 What can I do about it?我能做些什么呢?

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

Any ideas what am I missing in here?有什么想法我在这里缺少什么吗?

I think you need to omit the arrow function when passing the callback as prop like this我认为当像这样将回调作为道具传递时,您需要省略箭头 function

test={this.test}

I think you need to bind your function because you are using a class, try that:我认为您需要绑定您的 function 因为您使用的是 class,请尝试:

test={test.bind(this)}

Ok.好的。 Found the solution.找到了解决方案。 Object assign method for some reason fails to copy react callback '[native code]' issue. Object 分配方法由于某种原因无法复制反应回调“[本机代码]”问题。 I'll let the purist to debate on that.我会让纯粹主义者对此进行辩论。 I do not need the callback in this new object as it is passed further, and it is intended to have other properties, I simply clone the props myself with function removed ("zonk") in the example.我不需要这个新的 object 中的回调,因为它被进一步传递,并且它旨在具有其他属性,我只是自己克隆了道具,并在示例中删除了 function(“zonk”)。 Obviously this could be extended to verify the typeof key to make it more generic.显然,这可以扩展以验证 typeof 键以使其更通用。

updateState (props) {
  var distilledProps = _objectWithoutProperties(props, ['zonk'])
  console.log(distilledProps)
    const nextState = Object.assign({}, this.state, distilledProps, {
      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'
    })

... and helper function: ...和助手 function:

function _objectWithoutProperties(obj, keys) {
  var target = {};
  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }
  return target;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React router Route 组件 prop 抛出错误 - React router Route component prop throws an error 将 prop 从父组件传递给子组件时出错 - Error with passing a prop from parent to child component React 将 function 作为 prop 传递给子组件,但父组件未访问子组件提供的数据 - React Passing a function as prop to child component, but the parent is not accessing the data provided by the child 将 function 作为道具传递给 Typescript 反应功能组件 - Passing a function as a prop to a Typescript React Functional Component 将本机传递函数作为prop反映到子组件 - React Native pass function to child component as prop JavaScript React:将道具从子组件中的 function 传递到父组件中的 function 时出现问题 - JavaScript React: Issues with passing prop from a function in a child component to a function in the parent 在将 function 传递给子组件时,React 似乎只允许事件侦听器道具名称与 function 名称相同 - React seems to only allow the event listener prop name to be same as the function name when passing that function to the child component 从父组件传递道具在子组件 React 中变为空 - Passing a prop from a Parent component becomes null in the Child component React 将 object 的数组属性作为 React 组件 prop 传递会引发异常 - Passing an array attribute of an object as a React component prop throws an exception 在反应中传递状态或道具以将值传递给子组件 - Passing a state or prop to pass a value to child component in react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM