Reputation: 162
I set all the context of my main component from my child component and it works fine, but I don't know if this is correct
This is my main component
import Child from "./apps/child";
export default class NewTest extends Component {
constructor(){
super();
this.state={
one:1,
}
}
render() {
return (
<View style={styles.container}>
<Text>{this.state.one}</Text>
<Child root={this}/> //<----- Here i set all the context of my main Component to the child component
<TouchableOpacity onPress={()=>console.log(this.state.one)}>
<Text>Touch</Text>
</TouchableOpacity>
</View>
);
}
}
and this is my child component
export default class Child extends Component{
constructor(props){
super(props);
this.parent=this.props.root;
}
render(){
return(
<View>
<TouchableOpacity onPress={()=>{
this.parent.setState({one:this.parent.state.one+1}) // <- if you see here i change the state of the parent, and it work fine
}}>
<Text>Sum to Parent</Text>
</TouchableOpacity>
</View>
)
}
}
All this works, but is this the correct way to do it?
Upvotes: 0
Views: 143
Reputation: 2656
No, it's not. If you want to change the state of the parent component you should send a callback function as a prop to the child and then invoke it. For example, you could have a function in your NewTest:
increaseOne(){
this.setState({one:this.state.one+1})
}
Then, send it to the child with a prop:
<Child increaseOne={this.increaseOne.bind(this)}/>
Finally invoke it in the child onPress:
<TouchableOpacity onPress={this.props.increaseOne}>
If the application gets too complex, you could use Redux.
Upvotes: 5
Reputation: 1794
What you are trying to do, is to get full control over over component. This is not the best way to solve the problem, and the main reasoning that it will sooner or later strike you back. The idea is to pass hanlders via props, so they will be just invoked, but without any knowledge how they work.
So, in the code (function has to be bound already):
<Child increase={this.increase} decrease={this.decrease} />
With this approach you'll get much more easier to maintain and refactor solution – for instance, form can invoke passed submit function, which in the beginning can just fake it through setTimeout
, but later will be replaced with real call.
It also increases testability, looses coupling and leads to the better code in general.
Upvotes: 0
Reputation: 2263
It is not the best "React way" to do it. It would have been better to pass a function to the child component that should work as a callback (something like "sumToParent"); and the parent would react on it by making the sum.
Another option could be using react-router and react-redux to maintain the state.
Upvotes: 1