当前位置:首页 > React

react 兄弟组件如何通信

2026-01-24 07:32:31React

父子组件通信 vs 兄弟组件通信

React 中父子组件通信通过 props 传递数据,而兄弟组件之间没有直接通信方式,需要通过共同的父组件作为桥梁。

状态提升(Lifting State Up)

将共享状态提升到最近的共同父组件中,通过 props 向下传递数据,通过回调函数向上传递修改。

父组件示例:

function Parent() {
  const [sharedState, setSharedState] = useState('');

  return (
    <>
      <ChildA value={sharedState} />
      <ChildB onChange={setSharedState} />
    </>
  );
}

使用 Context API

当组件层级较深时,可以使用 Context 避免 prop drilling。

创建 Context:

const SharedContext = createContext();

function Parent() {
  const [value, setValue] = useState('');

  return (
    <SharedContext.Provider value={{ value, setValue }}>
      <ChildA />
      <ChildB />
    </SharedContext.Provider>
  );
}

子组件使用:

function ChildA() {
  const { value } = useContext(SharedContext);
  return <div>{value}</div>;
}

function ChildB() {
  const { setValue } = useContext(SharedContext);
  return <input onChange={e => setValue(e.target.value)} />;
}

使用状态管理库

对于复杂应用,Redux、MobX 或 Zustand 等库能更好地管理全局状态。

Zustand 示例:

const useStore = create(set => ({
  value: '',
  setValue: (newValue) => set({ value: newValue })
}));

function ChildA() {
  const value = useStore(state => state.value);
  return <div>{value}</div>;
}

function ChildB() {
  const setValue = useStore(state => state.setValue);
  return <input onChange={e => setValue(e.target.value)} />;
}

使用事件总线

通过自定义事件系统实现组件通信,适用于非父子关系的任意组件。

事件总线实现:

const events = {};

const eventBus = {
  on(event, callback) {
    if (!events[event]) events[event] = [];
    events[event].push(callback);
  },
  emit(event, data) {
    if (events[event]) events[event].forEach(cb => cb(data));
  }
};

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

// 组件B
eventBus.emit('update', 'new data');

使用 ref 和 forwardRef

通过 ref 直接访问组件实例方法(不推荐,破坏 React 数据流)。

父组件:

function Parent() {
  const childARef = useRef();
  const childBRef = useRef();

  return (
    <>
      <ChildA ref={childARef} />
      <ChildB ref={childBRef} />
    </>
  );
}

子组件:

react 兄弟组件如何通信

const ChildA = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    doSomething() {}
  }));
});

选择方法时应考虑组件关系复杂度、应用规模和维护成本。简单场景用状态提升,复杂场景推荐 Context 或状态管理库。

标签: 组件兄弟
分享给朋友:

相关文章

vue实现广告组件

vue实现广告组件

vue实现广告组件的方法 使用动态组件实现 在Vue中可以通过动态组件的方式加载广告组件,根据不同的条件展示不同的广告内容。动态组件使用<component :is="currentCompon…

如何设计react组件

如何设计react组件

设计 React 组件的核心原则 React 组件的设计需要遵循高内聚、低耦合的原则,确保组件功能独立且易于维护。组件的设计可以分为展示组件和容器组件两类,展示组件负责 UI 渲染,容器组件负责逻辑处…

如何缓存react组件

如何缓存react组件

缓存React组件的方法 React.memo 使用React.memo对函数组件进行浅比较缓存,避免不必要的重新渲染。适用于props不变的场景。 const MemoizedComponen…

vue实现搜索组件

vue实现搜索组件

Vue 实现搜索组件的方法 基础搜索组件实现 创建基础搜索组件需要包含输入框和搜索按钮。在Vue中可以使用v-model绑定输入值,通过@click或@keyup.enter触发搜索。 <te…

vue组件实现注册

vue组件实现注册

Vue 组件注册的两种方式 全局注册 通过 Vue.component() 方法注册,注册后可在任意 Vue 实例中使用。通常在项目的入口文件(如 main.js)中操作: import V…

vue实现组件拖动

vue实现组件拖动

Vue 实现组件拖动的几种方法 使用 HTML5 拖放 API HTML5 原生提供了拖放 API,可以通过 draggable 属性实现基础拖拽功能。在 Vue 中可以通过事件绑定实现交互逻辑。…