[英]How can i access function as a prop in child component that define in parent component?
I am trying to use a function as a prop in child component(DetailViewOfEntity)
that is defined in the parent component(App.js)
.我正在尝试使用 function 作为父
component(App.js)
中定义的子component(DetailViewOfEntity)
中的道具。 When I click on the button,I am getting an error that this.setState
and obj.detailview
is not defined.当我单击按钮时,我收到一个错误,即
this.setState
和obj.detailview
未定义。 Please also look at the image attached below for the exact error that I am getting.另请查看下面附上的图片,了解我得到的确切错误。
Thank you谢谢
App.js component 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 Component详细视图组件
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>
);
}
}
your problem is that you are calling:你的问题是你在打电话:
this.viewEntity = this.ViewEntity.bind(this);
instead of this.ViewEntity = this.ViewEntity.bind(this);
而不是
this.ViewEntity = this.ViewEntity.bind(this);
as @kapil pandey pointed out and here I share with you the working version on code sandbox正如@kapil pandey 指出的那样,在这里我与您分享代码沙箱上的工作版本
It's giving error because of function binding.由于 function 绑定,它给出了错误。 If you using 'create-react-app' , you can omit the constructor and use arrow function .
如果您使用'create-react-app' ,则可以省略构造函数并使用箭头 function 。 Hopefully, you won't give any error.
希望你不会给出任何错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.