So I have an app that looks like this (tried to simplify as much as possible):
// file with context
const SomeContext = React.createContext({});
// file with app root
class App extends Component {
constructor() {
super();
this.state = {
someValue: 123
};
}
doSomething() {
// this does not work,
// as "this" is context value
this.setState({
someValue: someValue + 1
});
}
render() {
// create context values
const value = {
someValue: this.state.someValue
doSomething: this.doSomething
};
return <SomeContext.Provider value={value}><ChildComponent/></SomeContext>;
}
}
// file with child component
class ChildComponent extends Component {
render() {
return <button onClick={this.context.doSomething} />
}
}
ChildComponent.contextType = SomeContext;
I want context to have doSomething
method that updates state of the app (specifically increase someValue
by 1).
How to correctly execute doSomething
method from child component?
Do I have to do doSomething: this.doSomething.bind(this)
? or there is a better way?
edit question is less about how to get "this", but more about what's the recommended way to do it in this case. Maybe I should not add method to context at all?