I'm probably asking the wrong question, but I'd like to be able to execute a parent function when called from a child function, not an event.
I have more or the less the following setup: Declaring the _foo method in the parent and passing it on down to ChildTwo, where executing it via an onClick event handler works as expected. However, I ran into a situation where I need to call the _foo method manually from inside another method (I've simplified it here, but it will be called conditionally).
My question is what do I need to do to call the _foo method from _bar() ?
Thanks in advance!
export defaultclass Parent extends Component {
constructor() {
super();
}
_foo() {
alert('alert!');
}
render() { <ChildOne _foo={this._foo.bind(this)} /> }
}
const ChildOne = (props) => {
const { _foo } = props;
return ( <ChildTwo _foo={_foo} /> );
}
export default class ChildTwo extends Component {
constructor(props) {
super(props);
this._foo = this.props._foo.bind(this);
}
_bar() {
//this._foo.call();
//this._foo();
//what do I do here?
}
render() {
return (
<div>
<button onClick={this._foo}> Works! </button>
<button onClick={this._bar}>Doesnt Work!</button>
</div>
);
}
};
<button onClick={this._foo}> Works! </button>or at least shouldn't really do anything, sincethis._foois undefined. I'm assuming it's just a typo in the example, so could you perhaps check your snippet again, to see if it matches your original code, and fix any typos?thisin the function body would reference the wrong object. So in yourChildTwo-component, you should add this line to your constructor:this._bar = this._bar.bind(this). Then you can go ahead and callthis._foo();in the body of_bar.