Skip to content Skip to sidebar Skip to footer

How To Bind 'this' To Functions Outside React Class Which Is A Callback From Other Component?

I have a React Component such as : function callback(params){.. // I need to use this.setstate but this callback function is called // from other component. How do I bind value of

Solution 1:

I don't really understand the question. I don't know if this is what you mean, but if you want to save the 'this' temporary variable, then just create a global array or single variable to store the 'this'.

var thisTemp;

function callback(params){..
// use variable here
thisTemp.blah();
...
}

classRespPropertiesextendsComponent { ..
//Assign this to thisTemp
thisTemp = this;
...
}

Solution 2:

You could separate this shared function, leaving it outside the components, then use bind:

functioncallback(params){
    this.setState({ works: true });
}

classRespPropertiesextendsComponent {
    state = { works: false }
    ...
    render = () =><buttononClick={callback.bind(this)}>Click</button>// ^ here we use .bind(this) to... well...//   bind `this` so we can use it in the function xD
}

classSomeOtherComponentextendsComponent {
    state = { works: false }
    ...
    render = () =><buttononClick={callback.bind(this)}>I'm from some other component</button>
}

Post a Comment for "How To Bind 'this' To Functions Outside React Class Which Is A Callback From Other Component?"