【问题标题】:Passing a function to a component but receiving undefined将函数传递给组件但接收未定义
【发布时间】:2018-11-05 19:01:47
【问题描述】:

在我的应用程序中,我需要将一个函数传递给“菜单”组件,该组件将在主组件内容区域中呈现必要的内容。

这是我在主要组件中所做的:

new Menu({ props: {contentComponentMounter: this.mountContentComponent}})

在我的菜单组件中,我有以下内容:

 constructor(props) {
        super(props);

        console.log(props, props.contentComponentMounter);    
    };

这是我得到的控制台输出:

如您所见,当我尝试记录 props 时,我看到了预期的结果,但对于 props.contentComponentMounter,它显示未定义。为什么会这样?

【问题讨论】:

标签: reactjs


【解决方案1】:

您需要将其称为props.props.contentComponentMounter。因为还要注意您的参数在此调用 { props: {contentComponentMounter: this.mountContentComponent}} 中的样子,所以可以从您的 console.log 输出中看到相同的内容。

如果您将参数作为new Menu({contentComponentMounter: this.mountContentComponent}) 传递给Menu 构造函数,您将不会得到未定义。

【讨论】:

    【解决方案2】:

    构造函数(道具){ 超级(道具);

        console.log(props, props.props.contentComponentMounter);    
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 2021-09-27
      • 2021-09-24
      相关资源
      最近更新 更多