我从子组件中设置了主组件的所有上下文,它工作正常,但我不知道这是否正确
这是我的主要组件
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>
);
}
}
这是我的子组件
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>
)
}
}
所有这些都有效,但是这是正确的方法吗?
最佳答案
不,不是。如果您想更改父组件的状态,您应该将回调函数作为 prop 发送给子组件,然后调用它。例如,您可以在 NewTest 中有一个函数:
increaseOne(){
this.setState({one:this.state.one+1})
}
然后,用 prop 将其发送给 child :
<Child increaseOne={this.increaseOne.bind(this)}/>
最后在子onPress中调用它:
<TouchableOpacity onPress={this.props.increaseOne}>
如果应用程序变得太复杂,您可以使用 Redux .
关于javascript - 这是在react.js中设置父组件状态的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40460085/