gpt4 book ai didi

javascript - 为什么 React 教程建议将子组件状态存储在父组件中?

转载 作者:太空宇宙 更新时间:2023-11-04 15:33:25 24 4
gpt4 key购买 nike

根据React教程https://facebook.github.io/react/tutorial/tutorial.html :

When you want to aggregate data from multiple children or to have two child components communicate with each other, move the state upwards so that it lives in the parent component. The parent can then pass the state back down to the children via props, so that the child components are always in sync with each other and with the parent.

这似乎与良好的 OOP 实践相矛盾,其中每个对象都维护自己的状态。

最佳答案

When you want to aggregate data from multiple children or to have two child components communicate with each other, move the state upwards so that it lives in the parent component. The parent can then pass the state back down to the children via props, so that the child components are always in sync with each other and with the parent.

考虑一个父级有两个子级的情况,其结构如下

<Parent>
<Child1/>
<Child2/>
</Parent>

现在 Child1 只有 input 组件,Child2 显示在输入中输入的内容

在这种情况下,如果将输入值保留在 Child1 中,则无法从 Parent 访问它,因为状态是组件的本地属性并且是私有(private)属性。因此,将属性保留在父级中,然后将其作为 Prop 传递给子级,以便两个子级都可以使用它是有意义的

示例片段

class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
inputVal: ''
}
}
handleChange = (val) => {
this.setState({inputVal: val});
}
render() {
return (
<div>
<Child1 handleChange={this.handleChange} inpVal={this.state.inputVal}/>
<Child2 value={this.state.inputVal}/>
</div>
)
}
}

class Child1 extends React.Component {

render() {
return (
<div>
<input type="text" value={this.props.inpVal} onChange={(e) => this.props.handleChange(e.target.value)} />
</div>
)
}
}

class Child2 extends React.Component {

render() {
return (
<div>
{this.props.value}
</div>
)
}
}

ReactDOM.render(<Parent/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></app>

关于javascript - 为什么 React 教程建议将子组件状态存储在父组件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44611905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com