当前位置:首页 > React

react组件之间是如何通信

2026-01-25 04:11:57React

父子组件通信(Props)

父组件通过props向子组件传递数据或方法,子组件通过接收props实现数据或行为的更新。父组件定义props,子组件通过this.props(类组件)或直接解构(函数组件)访问。

// 父组件
function Parent() {
  const [data, setData] = useState("Hello");
  return <Child message={data} />;
}

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

子父组件通信(回调函数)

子组件通过调用父组件传递的回调函数,将数据传递回父组件。父组件定义回调方法并传递给子组件,子组件在适当时机触发回调。

react组件之间是如何通信

// 父组件
function Parent() {
  const handleChildEvent = (data) => {
    console.log("Received:", data);
  };
  return <Child onEvent={handleChildEvent} />;
}

// 子组件
function Child({ onEvent }) {
  return <button onClick={() => onEvent("Data")}>Send</button>;
}

跨层级组件通信(Context API)

使用React的Context API实现跨层级组件通信,避免props逐层传递。通过createContext创建上下文,Provider提供数据,ConsumeruseContext消费数据。

const MyContext = createContext();

// 顶层组件
function App() {
  return (
    <MyContext.Provider value="Shared Data">
      <IntermediateComponent />
    </MyContext.Provider>
  );
}

// 底层组件
function DeepChild() {
  const value = useContext(MyContext);
  return <div>{value}</div>;
}

全局状态管理(Redux/MobX)

复杂应用中使用Redux或MobX等状态管理库。Redux通过单一store集中管理状态,组件通过connectuseSelector访问状态,通过dispatch触发更新。

react组件之间是如何通信

// Redux示例
import { useSelector, useDispatch } from 'react-redux';

function Counter() {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();
  return (
    <button onClick={() => dispatch({ type: 'INCREMENT' })}>
      {count}
    </button>
  );
}

事件总线(Event Emitter)

通过自定义事件总线实现任意组件间通信。创建一个全局事件管理器,组件通过订阅和发布事件交互。

// 事件总线实现
const events = {};
const eventBus = {
  on(event, callback) {
    events[event] = events[event] || [];
    events[event].push(callback);
  },
  emit(event, data) {
    events[event]?.forEach(callback => callback(data));
  }
};

// 组件A
eventBus.on("update", data => console.log(data));

// 组件B
eventBus.emit("update", "New Data");

Refs与DOM操作

父组件通过ref直接访问子组件的DOM节点或方法。类组件使用React.createRef,函数组件使用useRef

// 父组件
function Parent() {
  const childRef = useRef();
  const focusChild = () => childRef.current.focus();
  return (
    <>
      <Child ref={childRef} />
      <button onClick={focusChild}>Focus</button>
    </>
  );
}

// 子组件(需使用forwardRef)
const Child = forwardRef((props, ref) => {
  return <input ref={ref} />;
});

标签: 组件通信
分享给朋友:

相关文章

vue 组件实现

vue 组件实现

Vue 组件实现方法 单文件组件 (SFC) 使用 .vue 文件格式,包含模板、脚本和样式三部分: <template> <div class="example">{…

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

Vue 拖拽实现组件嵌套 使用 Vue 实现拖拽组件嵌套功能可以通过原生 HTML5 拖拽 API 或第三方库如 vuedraggable 实现。以下是两种方法的详细说明: 使用 HTML5 拖拽…

vue轮播组件实现

vue轮播组件实现

Vue 轮播组件实现方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template…

vue实现折叠组件

vue实现折叠组件

Vue 折叠组件实现方法 基于 v-show 和事件触发 通过 v-show 控制内容的显示与隐藏,结合点击事件切换状态。 <template> <div> &…

vue实现组件循环图片

vue实现组件循环图片

Vue 实现组件循环图片的方法 在 Vue 中实现组件循环图片通常可以通过 v-for 指令结合动态数据绑定完成。以下是几种常见的实现方式: 使用静态图片路径数组 假设有一组本地图片路径,可以通过…

vue组件实现

vue组件实现

Vue 组件实现 Vue 组件是 Vue.js 的核心特性之一,允许开发者将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种常见方式: 单文件组件(SFC) 单文件组件是 Vue 中…