REACT:如何将 child 组件的状态设置为其 parent 的状态?

REACT: How do you set a child component's state to its parent's state?

我希望 child 组件的状态随着 parent 组件的状态更新而更新。 parent 状态变量的任何更改都应反映在 child 的状态中。我该怎么做?

谢谢!

编辑:

我的组件按以下方式排列。我想从 Child 2 访问 parent 的状态。通过将 Child 1 状态设置为 parent 的状态,我将能够做到这一点.

Parent->Child 1->Child 2

您可以将您需要的父状态部分作为道具传递给子状态。 然后每次父状态改变时,子状态将重新呈现正确的值。

如果您需要从子项内部更改状态,这取决于您想要的行为。

您可以通过将回调函数作为 prop 传递给子级来使子级更改父级状态(您可以将父级中用于更改状态的函数作为 prop 传递给子级)

或者您可以通过使用 useEffect 或 ComponentDidUpdate 侦听 prop 上的更改,使子本地状态在更改时重置为父状态。

useEffect(() => { setState(props.partOfparentState)},[props.partOfparentState])

ComponentDidUpdate(prevProps) {
    if(previousProps.partOfParentState != props.partOfParentState) {
        partOfParentStatethis.setState({state:props.parpartOfParentStatetOfParentState})
    }
}

您可能还需要其他可以通过更复杂的 useEffect 实现的行为。

状态和道具

React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

the data flow in react is “unidirectional” or “top-down”, Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.

If you imagine a component tree as a waterfall of props, each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.

This is why the state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it. @reactjs

因此,您应该将状态传递给 child 组件,也称为 prop

编辑:

层次结构将是这样的: App(state - date) => Child1(prop date, 传递相同的 prop 到下一个 child) => Child2(从他的 parent - Child1)

示例(基于Class Components):

<App>:

应用程序的根目录。

<ClockList date={this.state.date} />

<ClockList>:

注意我们正在使用道具

<Clock date={this.props.date} />

<Clock>:

import React from "react";

const Clock = (props) => {
  // Object Destructuring can also be done in the function itself.
  const { date } = props;
  return (
    <div className="container">
      <p>{date}</p>
    </div>
  );
};

export default Clock;