在我的 App.js 中,我已经初始化了一些状态,如下所示,
export default class App extends React.Component {
constructor(){
super();
this.state = {
myfirststate: '',
mysecondstate: '',
}
}
...
}
现在我有一个无状态的 ChildComponent.js,就像这样,它有一个按钮,单击时,会将 myfirststate
的状态从 null 更改为 hello
。
export default class ChildComponent extends React.Component {
render() {
return (
<View>
<Button
title="clickme"
onPress={() =>
this.setState({myfirststate: "hello"})
/>
</View>
);
}
}
可以做这样的事情吗?我一直认为我必须将状态值作为参数传递到函数中,该函数从父组件传递到子组件,就像这样。
App.js
export default class App extends React.Component {
constructor(){
super();
this.state = {
myfirststate: '',
mysecondstate: '',
}
}
functiontopassvalues(values) {
this.setState({
myfirststate: values
})
}
<ChildComponent functiontopassvalues={this.functiontopassvalues} />
}
在 ChildComponent.js
中我会做这样的事情
export default class ChildComponent extends React.Component {
render() {
return (
<View>
<Button
title="clickme"
onPress={() =>
{this.props.functiontopassvalues("hello")}
/>
</View>
);
}
}
我希望我说得有道理,请让我知道正确的方法是什么以及为什么会这样。另外,它是否适用于 React Native 和 React.js?
最佳答案
您解决问题的方式是公平且正确的,但它不一定是可扩展的,并且您是正确的,因为您无法改变 child 中 parent 的状态。
我建议查看类似 Redux 的工具, MobX或Apollo Link State这一切都试图解决状态管理的永恒问题。
关于javascript - 是否可以在 React Native 中从其无状态组件子级更改父级的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49250651/