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

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.lryc.cn/news/533291.html

相关文章:

  • FastReport 加载Load(Stream) 模板内包含换行符不能展示
  • Maven 中常用的 scope 类型及其解析
  • vue3:点击子组件进行父子通信
  • Composo:企业级AI应用的质量守门员
  • Jackson扁平化处理对象
  • Java即时编译器(JIT)的原理及在美团的实践经验
  • 使用 Ollama 在 Windows 环境部署 DeepSeek 大模型实战指南
  • 算法基础之八大排序
  • 使用TensorFlow和Keras构建卷积神经网络:图像分类实战指南
  • 音频进阶学习十一——离散傅里叶级数DFS
  • 20.<Spring图书管理系统①(登录+添加图书)>
  • 关于图像锐化的一份介绍
  • Django开发入门 – 0.Django基本介绍
  • 多智能体协作架构模式:驱动传统公司向AI智能公司转型
  • CentOS服务器部署Docker+Jenkins持续集成环境
  • 【prompt实战】AI +OCR技术结合ChatGPT能力项目实践(BOL提单识别提取专家)
  • 【Android】Android开发应用如何开启任务栏消息通知
  • 上传文件报错:the request was rejected because no multipart boundary was found
  • 大模型—Dify本地化部署实战
  • 功能架构元模型
  • 常用工具类——Collections集合框架
  • e2studio开发RA2E1(9)----定时器GPT配置输入捕获
  • 25/2/7 <机器人基础>雅可比矩阵计算 雅可比伪逆
  • 网络爬虫js逆向之异步栈跟栈案例
  • 使用Ollama本地部署deepseek
  • Rust错误处理:从灭火器到核按钮的生存指南
  • Golang:Go 1.23 版本新特性介绍
  • 电脑运行黑屏是什么原因?原因及解决方法
  • redis之AOF持久化过程
  • Elasticsearch:向量搜索的快速介绍