react 兄弟组件如何通信
兄弟组件通信方法
在React中,兄弟组件之间直接通信需要通过共同的父组件作为中介。以下是几种常见的实现方式:
状态提升(Lifting State Up)
将共享状态提升到最近的共同父组件中,通过props传递给子组件。父组件管理状态,子组件通过回调函数修改状态。
function Parent() {
const [sharedState, setSharedState] = useState('');
return (
<>
<ChildA
state={sharedState}
onStateChange={setSharedState}
/>
<ChildB
state={sharedState}
onStateChange={setSharedState}
/>
</>
);
}
Context API
使用React的Context API创建全局状态,兄弟组件都可以订阅和更新该状态。
const MyContext = createContext();
function Parent() {
const [value, setValue] = useState('');
return (
<MyContext.Provider value={{ value, setValue }}>
<ChildA />
<ChildB />
</MyContext.Provider>
);
}
function ChildA() {
const { setValue } = useContext(MyContext);
return <button onClick={() => setValue('A')}>Update</button>;
}
function ChildB() {
const { value } = useContext(MyContext);
return <div>{value}</div>;
}
事件总线(Event Bus)
创建一个全局事件发射器,兄弟组件通过订阅和触发事件进行通信。
const EventEmitter = require('events');
const eventBus = new EventEmitter();
function ChildA() {
const handleClick = () => {
eventBus.emit('event', 'data');
};
return <button onClick={handleClick}>Send</button>;
}
function ChildB() {
const [data, setData] = useState('');
useEffect(() => {
eventBus.on('event', setData);
return () => eventBus.off('event', setData);
}, []);
return <div>{data}</div>;
}
状态管理库
使用Redux、MobX等状态管理库集中管理应用状态,兄弟组件通过连接store进行通信。
// Redux示例
import { useSelector, useDispatch } from 'react-redux';
function ChildA() {
const dispatch = useDispatch();
return (
<button onClick={() => dispatch({ type: 'UPDATE' })}>
Dispatch
</button>
);
}
function ChildB() {
const state = useSelector(state => state.value);
return <div>{state}</div>;
}
useReducer + Context
结合useReducer和Context创建更复杂的状态管理方案。

const StateContext = createContext();
const DispatchContext = createContext();
function reducer(state, action) {
switch(action.type) {
case 'UPDATE':
return { ...state, value: action.payload };
default:
return state;
}
}
function Parent() {
const [state, dispatch] = useReducer(reducer, { value: '' });
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>
<ChildA />
<ChildB />
</DispatchContext.Provider>
</StateContext.Provider>
);
}
方法选择建议
- 简单场景:状态提升或Context API
- 中等复杂度:useReducer + Context
- 大型应用:Redux等状态管理库
- 解耦需求:事件总线模式
每种方法都有其适用场景,应根据项目规模和组件关系复杂度选择最合适的方案。






