I want to decouple the event handler state change logic from React Component A and put it inside class B. class B (so not a React component) should be able to change state of component A.
So I don't want to pass function reference setState(B.handle) to setState but be able to setState from class B.
How to do it?
Is passing this to constructor of class B the way to go?
edit: sorry, forgot to mention that i can't use third party libraries to keep it dependencies free.
The usual way to set state from another component, is through a state engine like redux. When a state gets changed, if multiple components are watching the state, it can update each component that cares about that slice of the application state.
In the latest versions of React, they introduced contexts, which provide similar functionality.
I think we can use refs: https://reactjs.org/docs/refs-and-the-dom.html
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
.... // Somewhere
this.myRef.setState(newState);
...
render() {
return <ChildComponent ref={this.myRef} />;
}
}
To make changes to the props: https://facebook.github.io/react-native/docs/direct-manipulation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With