react兄弟组件如何通信
兄弟组件通信的方法
在React中,兄弟组件之间无法直接通信,需要通过共同的父组件作为中介。以下是几种常用的方法:
通过父组件传递状态
父组件维护共享状态,并通过props传递给子组件。子组件通过回调函数修改父组件的状态,从而触发兄弟组件的更新。

function Parent() {
const [sharedState, setSharedState] = useState('');
return (
<>
<ChildA state={sharedState} setState={setSharedState} />
<ChildB state={sharedState} />
</>
);
}
function ChildA({ state, setState }) {
return <input value={state} onChange={(e) => setState(e.target.value)} />;
}
function ChildB({ state }) {
return <div>{state}</div>;
}
使用Context API
当组件层级较深时,可以使用Context避免props逐层传递。

const MyContext = createContext();
function Parent() {
const [sharedState, setSharedState] = useState('');
return (
<MyContext.Provider value={{ sharedState, setSharedState }}>
<ChildA />
<ChildB />
</MyContext.Provider>
);
}
function ChildA() {
const { setSharedState } = useContext(MyContext);
return <input onChange={(e) => setSharedState(e.target.value)} />;
}
function ChildB() {
const { sharedState } = useContext(MyContext);
return <div>{sharedState}</div>;
}
使用状态管理库
对于复杂应用,可以使用Redux、MobX或Zustand等状态管理库。
// 使用Zustand示例
import create from 'zustand';
const useStore = create(set => ({
sharedState: '',
setSharedState: (value) => set({ sharedState: value })
}));
function ChildA() {
const setSharedState = useStore(state => state.setSharedState);
return <input onChange={(e) => setSharedState(e.target.value)} />;
}
function ChildB() {
const sharedState = useStore(state => state.sharedState);
return <div>{sharedState}</div>;
}
使用事件总线
通过自定义事件系统实现组件间通信。
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(callback => callback(data));
}
};
function ChildA() {
return <input onChange={(e) => eventBus.emit('update', e.target.value)} />;
}
function ChildB() {
const [value, setValue] = useState('');
useEffect(() => {
eventBus.on('update', setValue);
return () => eventBus.off('update', setValue);
}, []);
return <div>{value}</div>;
}
每种方法适用于不同场景,简单场景使用父组件状态传递即可,复杂应用建议使用状态管理库。






