react 18父子组件通信

发布于:2025-02-10 ⋅ 阅读:(34) ⋅ 点赞:(0)

在React 18中,父子组件之间的通信方式与之前的版本基本相同,主要可以通过以下几种方式实现:

1. Props(属性)

父组件向子组件传递数据:

父组件通过属性(props)向子组件传递数据,子组件通过props接收数据。

// 父组件
function ParentComponent() {
  const message = "Hello from Parent";

  return <ChildComponent message={message} />;
}

// 子组件
function ChildComponent({ message }) {
  return <div>{message}</div>;
}

子组件向父组件传递数据:

子组件通过调用父组件传递下来的函数来传递数据。

// 父组件
function ParentComponent() {
  const handleReceiveData = (data) => {
    console.log("Received data from child:", data);
  };

  return <ChildComponent onReceiveData={handleReceiveData} />;
}

// 子组件
function ChildComponent({ onReceiveData }) {
  const data = "Hello from Child";

  return <button onClick={() => onReceiveData(data)}>Send Data to Parent</button>;
}

2. Context(上下文)

当需要在多个层级的组件之间传递数据时,可以使用Context。

// 创建Context
const MyContext = React.createContext();

// 父组件
function ParentComponent() {
  const message = "Hello from Parent";

  return (
    <MyContext.Provider value={message}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

// 子组件
function ChildComponent() {
  const message = useContext(MyContext);

  return <div>{message}</div>;
}

3.Refs(引用)

如果需要直接在父组件中操作子组件的DOM或状态,可以使用Refs。

// 父组件
function ParentComponent() {
  const childRef = useRef(null);

  const handleParentClick = () => {
    if (childRef.current) {
      childRef.current.childMethod();
    }
  };

  return (
    <>
      <ChildComponent ref={childRef} />
      <button onClick={handleParentClick}>Call Child Method</button>
    </>
  );
}

// 子组件
const ChildComponent = forwardRef((props, ref) => {
  const childMethod = () => {
    console.log("Child method called");
  };

  useImperativeHandle(ref, () => ({
    childMethod,
  }));

  return <div>Child Component</div>;
});

4. State Lift(状态提升)

当多个子组件需要共享状态时,可以将状态提升到它们的共同父组件中管理。

// 父组件
function ParentComponent() {
  const [sharedState, setSharedState] = useState("initial state");

  const updateState = (newState) => {
    setSharedState(newState);
  };

  return (
    <>
      <ChildComponentA sharedState={sharedState} updateState={updateState} />
      <ChildComponentB sharedState={sharedState} updateState={updateState} />
    </>
  );
}

// 子组件A
function ChildComponentA({ sharedState, updateState }) {
  return <button onClick={() => updateState("New state from A")}>Update State from A</button>;
}

// 子组件B
function ChildComponentB({ sharedState }) {
  return <div>Shared State: {sharedState}</div>;
}

在React 18中,这些通信方式仍然有效,并且可以结合使用以满足不同的需求。选择哪种方式取决于你的具体场景和组件结构。