react 兄弟组件如何通信
父子组件通信 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} />
</>
);
}
子组件:
const ChildA = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
doSomething() {}
}));
});
选择方法时应考虑组件关系复杂度、应用规模和维护成本。简单场景用状态提升,复杂场景推荐 Context 或状态管理库。






