I am trying to use a function as a prop in child component(DetailViewOfEntity)
that is defined in the parent component(App.js)
. When I click on the button,I am getting an error that this.setState
and obj.detailview
is not defined. Please also look at the image attached below for the exact error that I am getting.
Thank you
App.js component
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);
as @kapil pandey pointed out and here I share with you the working version on code sandbox
It's giving error because of function binding. If you using 'create-react-app' , you can omit the constructor and use arrow function . Hopefully, you won't give any error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.