如何在父组件中定义的子组件中访问作为道具的功能?

时间:2020-07-21 09:19:13

标签: javascript reactjs

我正在尝试在父项component(DetailViewOfEntity)中定义的子项component(App.js)中使用函数作为道具。当我单击按钮时,出现错误,提示未定义this.setStateobj.detailview。另外,请查看下面所附的图片,了解我得到的确切错误。

谢谢

App.js组件

import  React from "react";

import DetailViewOfEntity from "./DetailViewOfEntity";


export default class App extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.viewEntity = this.ViewEntity.bind(this);

    this.state = {

        viewEntityState: false,
    
    };

  }


  }
  
  ViewEntity (para) {
    var obj = this;
    this.setState ({
      viewEntityState: true,
    });                                      

    obj.DetailView();//another function
  }

  DetailView() {
    console.log("we are in detail view function");
  }


  render() {

    return (
      <div>
        
        <DetailViewOfEntity 
            test = {this.ViewEntity}
        /> 
      </div>
    );
  }
}

DetailView组件

import React from "react";

export default class DetailViewOfEntity extends React.Component {
    constructor (props, context) {
        super (props, context);
    }

    UpdateCommentsFromCRM() {

        this.props.test(); //when i call this function, i got an error.
    }
  render () { 
      return (
          <div>

            <button onClick = {() => this.UpdateCommentsFromCRM()}>
            </button>
                     
          </div>
      );
  }
}

enter image description here

2 个答案:

答案 0 :(得分:1)

您的问题是您在打电话:
this.viewEntity = this.ViewEntity.bind(this); 代替 this.ViewEntity = this.ViewEntity.bind(this);

@kapil pandey指出,在这里我与您分享代码沙箱上的工作版本

codesandbox demo

答案 1 :(得分:0)

由于函数绑定,它给出了错误。如果您使用'create-react-app',则可以省略构造函数并使用箭头功能。希望您不会出错。