React: Can't Call Prop Function When It Is Inside Of Another Function?
Then:
login() {
this.props.route.auth.login();
}
I edited the answer so that it uses an arrow function. However, I prefer not doing that, since it makes the code a bit cumbersome, and rather bind
all the functions in the constructor, like @patrick-w-mcmahon did.
Solution 2:
Let's say you have a container MyContainer and this container renders a view called MyView. This view has a button that calls a method. MyContainer is going to pass to the MyView the method it needs to use.
MyContainer:
class MyContainer extends React.Component {
constructor(props) {
super(props);
this.myFunc = this.myFunc.bind(this);
}
myFunc() {
console.log("hello world");
}
render() {
return <MyView myClick={this.myFunc}/>;
}
}
MyView:
const MyView = ({ myClick }) => {
return <button onClick={myClick} />;
};
MyView.propTypes = {
myClick: PropTypes.func
};
export default MyView;
You pass the needed function from the container to the view and the view calls its parents function from props. the use of bind() sets this scope to the current scope so that when you call this from a different scope it is going to be the scope of the bind. When you are in the render you run a different scope so you must bind your functions to the current class scope so that this.myReallyCoolFunction() is pointing to the correct scope (your class scope).
Solution 3:
.bind()
will only bind the object and arguments but won't call (run) the function.
TL;DR Just use .call()
instead of .bind()
instead of .bind()
you can use
.call(this, args)
which is basicaly the same as bind only that call
will call (run) the function.
you could also use .apply()
, which is basicaly the same as .call()
but takes an array with the arguments instead of object like .call()
this way you can avoid arrow functions in you jsx render() and kind of keeping the line of thought with react.
something like ->
login() {
this.props.route.auth.login.call(this);
}
When you call props function through return(JSX) React takes care of calling it once propagation ends.
Post a Comment for "React: Can't Call Prop Function When It Is Inside Of Another Function?"