我正在尝试在父项component(DetailViewOfEntity)
中定义的子项component(App.js)
中使用函数作为道具。当我单击按钮时,出现错误,提示未定义this.setState
和obj.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>
);
}
}
答案 0 :(得分:1)
您的问题是您在打电话:
this.viewEntity = this.ViewEntity.bind(this);
代替
this.ViewEntity = this.ViewEntity.bind(this);
@kapil pandey指出,在这里我与您分享代码沙箱上的工作版本
答案 1 :(得分:0)
由于函数绑定,它给出了错误。如果您使用'create-react-app',则可以省略构造函数并使用箭头功能。希望您不会出错。