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

react+ts中函数组件父子通信方式

1. 父组件通过 Props 向子组件传递数据

这是最常见也是最基本的父子组件通信方式。父组件通过 props 将数据或回调函数传递给子组件。

示例代码:
// 子组件接收来自父组件的数据
interface ChildProps {message: string;
}const ChildComponent: React.FC<ChildProps> = ({ message }) => {return <h1>{message}</h1>;
};// 父组件向子组件传递数据
const ParentComponent = () => {const parentMessage = "Hello from Parent!";return (<ChildComponent message={parentMessage} />);
};

2. 子组件通过回调函数通知父组件

如果子组件需要与父组件交互,则可以通过父组件传递一个回调函数作为 prop,在子组件中调用该函数以通知父组件某些事件的发生。

示例代码:
interface ChildProps {onButtonClick: () => void;
}const ChildComponent: React.FC<ChildProps> = ({ onButtonClick }) => {return (<button onClick={onButtonClick}>Click Me to Notify Parent</button>);
};// 父组件提供回调函数处理逻辑
const ParentComponent = () => {const notifyParent = () => {console.log("Button clicked in child component!");};return (<ChildComponent onButtonClick={notifyParent} />);
};
3. 使用 Refs 访问子组件实例

虽然不建议频繁使用 refs 来管理子组件的状态或行为,但在特殊场景下仍然可行。可以结合 React.forwardRefuseImperativeHandle 来暴露子组件的功能供父组件调用。

示例代码:
// 子组件定义并通过 forwardRef 曝露功能
interface ChildProps{}const ChildComponent = React.forwardRef((props:ChildProps, ref) => {const [count, setCount] = React.useState(0);// 暴露方法给父组件React.useImperativeHandle(ref, () => ({increment() {setCount(count + 1);},}));return <div>Current Count: {count}</div>;
});export default ChildComponent;// 父组件利用 useRef 获取子组件实例
const ParentComponent = () => {const childRef = React.useRef<any>();const handleClickIncrement = () => {childRef.current?.increment();};return (<><button onClick={handleClickIncrement}>Increment Child State</button><ChildComponent ref={childRef} /></>);
};
4. 使用 Context 提供全局状态共享

对于复杂的应用程序结构,可能涉及多个层级间的通信需求。此时可以采用上下文 API (React.createContext) 来简化跨层通信过程。

示例代码:
// 创建 context 并设置默认值
const MyContext = React.createContext<string | null>(null);// Provider 组件封装状态
const ContextProvider = ({ children }: { children: React.ReactNode }) => {const [value, setValue] = React.useState("Initial Value");return (<MyContext.Provider value={value}>{children}</MyContext.Provider>);
};// 子组件消费 context 数据
const ChildComponent = () => {const contextValue = React.useContext(MyContext);return <p>Received From Context: {contextValue}</p>;
};// 父组件嵌套 provider 及消费者
const ParentComponent = () => {return (<ContextProvider><ChildComponent /></ContextProvider>);
};

http://www.xdnf.cn/news/324595.html

相关文章:

  • C#——NET Core 中实现汉字转拼音
  • Spring MVC Controller 方法的返回类型有哪些?
  • 项目优先级频繁变动,如何应对?
  • C++入门之认识整型
  • 使用OpenCV 和 Dlib 实现人脸融合技术
  • shell(11)
  • 使用ffmpeg截取MP3等音频片段
  • MCP Client适配DeepSeek
  • SpringBoot 集成 Ehcache 实现本地缓存
  • Vue3 自定义指令的原理,以及应用
  • Ubuntu 单机多卡部署脚本: vLLM + DeepSeek 70B
  • ERP进销存系统源码,SaaS模式多租户ERP管理系统,SpringBoot、Vue、UniAPP技术框架
  • 基于nnom的多选择器
  • springboot国家化多语言实现
  • mybatis-plus分页查询count语句为什么没有left join
  • 正则表达式非捕获分组?:
  • CHAPTER 17 Iterators, Generators, and Classic Coroutines
  • 构建高质量数据湖:大数据治理在湖仓一体架构下的实践指南
  • mathtype转化
  • Vivo 手机官网交互效果实现解析
  • arXiv论文 MALOnt: An Ontology for Malware Threat Intelligence
  • ubuntu中解决matplotlib无法显示中文问题
  • 【MVCP】基于解纠缠表示学习和跨模态-上下文关联挖掘的多模态情感分析
  • 码蹄集——平方根X、整除幸运数
  • Rust 与 Golang 深度对决:从语法到应用场景的全方位解析
  • 平面坐标系中判断点P是否在线段上AB上的常用方法总结
  • 【渗透测试】命令执行漏洞的原理、利用方式、防范措施
  • 滚动条样式
  • 数据治理与数据资产管理研究方向展望
  • 【java】使用iText实现pdf文件增加水印功能