当前位置: 首页 > 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>);
};

相关文章:

  • React Fiber
  • Canal mysql to mysql 增加 online 库同步配置指南
  • 【基础】Python包管理工具uv使用全教程
  • 13前端项目----购物车修改
  • MySQL初阶:基础增删改查(CRUD)
  • vue3使用轮播图组件swiper
  • 2.Redis高阶实战
  • On the Biology of a Large Language Model——论文学习笔记——拒答和越狱
  • 点分治解析
  • Python __new__ 一个特殊的静态方法
  • 使用Windows+Linux实现mysql的主从复制
  • LangChain入门(六)Agent
  • day5:nginx代理-动静分离
  • 【了解】通感算一体化网络
  • Selenium模拟人类行为,操作网页的方法(全)
  • 每日算法-250506
  • 大模型系列(三)--- ​ GPT1: Improving Language Understanding by Generative Pre-Training​
  • 【HarmonyOS 5】鸿蒙用户头像编辑功能实践
  • 基于【抖音弹幕抓取数据推送】——制作抖音消息分类查看界面
  • YOLOv8的Python基础--函数篇
  • 保证断电、碰撞等事故中车门系统能够开启!汽车车门把手将迎来强制性国家标准
  • 马新民卸任外交部条约法律司司长
  • 司法部:建立行政执法监督企业联系点,推行行政执法监督员制度
  • 对话|蓬皮杜策展人布莱昂:抽象风景中的中国审美
  • 中科院院士魏辅文已卸任江西农业大学校长
  • 数据中心业务今年预增50%,丹佛斯:中国是全球最重要的市场