当前位置: 首页 > article >正文

react 18父子组件通信

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


http://www.kler.cn/a/540049.html

相关文章:

  • 2月10日QT
  • 微信小程序案例2——天气微信小程序(学会绑定数据)
  • ubuntu文件同步
  • DeepSeek从入门到精通:全面掌握AI大模型的核心能力
  • Academy Sports + Outdoors EDI:体育零售巨头的供应链“中枢神经”
  • 第六届MathorCup高校数学建模挑战赛-A题:淡水养殖池塘水华发生及池水自净化研究
  • PHP音视频课程培训系统
  • Cesium 离线加载瓦片图
  • pytest+request+yaml+allure 接口自动化测试全解析[手动写的跟AI的对比]
  • collabora online+nextcloud+mariadb在线文档协助
  • HTTP/3与QUIC的关系是什么?
  • 如何排查主板硬件问题的常见方法?
  • ESP32S3读取数字麦克风INMP441的音频数据
  • LeetCode 3444.使数组包含目标值倍数的最小增量
  • 安装mariadb+galera搭建数据库集群
  • 安全研究员职业提升路径
  • 运维_Mac环境单体服务Docker部署实战手册
  • 《手札·开源篇》数字化转型助力永磁电机企业降本增效:快速设计软件如何让研发效率提升40%?
  • ElementUI的常用组件及使用技巧
  • 微服务..
  • HTML与CSS常见问题总结
  • MAC国内安装Homebrew的方法
  • 【LeetCode 刷题】动态规划(2)-背包问题
  • 【自开发工具】SQLSERVER的ImpDp和ExpDp工具汇总
  • DeepSeek时代:百度们亟需“深度求索”
  • 信息科技伦理与道德3-3:智能决策