react兄弟组件如何通信
父子组件通信
父组件通过props向子组件传递数据,子组件通过回调函数通知父组件。这是React中最基础的通信方式,适用于直接嵌套的组件关系。
// 父组件
function Parent() {
const [data, setData] = useState('initial');
const handleChildUpdate = (newData) => {
setData(newData);
};
return <Child data={data} onUpdate={handleChildUpdate} />;
}
// 子组件
function Child({ data, onUpdate }) {
return (
<button onClick={() => onUpdate('updated')}>
{data}
</button>
);
}
Context API
使用React内置的Context实现跨层级组件通信。创建Context后,Provider组件提供数据,Consumer组件或useContext钩子消费数据。
const DataContext = createContext();
// 顶层组件
function App() {
const [value, setValue] = useState('default');
return (
<DataContext.Provider value={{ value, setValue }}>
<ComponentA />
<ComponentB />
</DataContext.Provider>
);
}
// 任意子组件
function ComponentA() {
const { value } = useContext(DataContext);
return <div>{value}</div>;
}
function ComponentB() {
const { setValue } = useContext(DataContext);
return <button onClick={() => setValue('new')}>Update</button>;
}
状态管理库
Redux或MobX等状态管理库适用于复杂应用场景。这些库提供全局状态管理,所有组件都可以订阅和修改共享状态。
// Redux示例
import { useSelector, useDispatch } from 'react-redux';
function ComponentA() {
const data = useSelector(state => state.data);
return <div>{data}</div>;
}
function ComponentB() {
const dispatch = useDispatch();
return (
<button onClick={() => dispatch({ type: 'UPDATE' })}>
Update
</button>
);
}
事件总线
通过自定义事件系统实现组件通信。这种方式不依赖组件层级关系,但需要手动管理订阅和取消订阅。
const eventBus = new EventEmitter();
function ComponentA() {
const [message, setMessage] = useState('');
useEffect(() => {
const handler = (msg) => setMessage(msg);
eventBus.on('message', handler);
return () => eventBus.off('message', handler);
}, []);
return <div>{message}</div>;
}
function ComponentB() {
return (
<button onClick={() => eventBus.emit('message', 'Hello')}>
Send
</button>
);
}
状态提升
将共享状态提升到最近的共同祖先组件中。适用于需要共享状态的兄弟组件,通过props和回调实现数据同步。
function Parent() {
const [sharedState, setSharedState] = useState(null);
return (
<>
<ChildA
state={sharedState}
onStateChange={setSharedState}
/>
<ChildB
state={sharedState}
onStateChange={setSharedState}
/>
</>
);
}
引用传递
使用forwardRef和useImperativeHandle暴露子组件方法,允许父组件直接调用子组件函数。
// 子组件
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
doSomething: () => console.log('Action performed')
}));
return <div>Child</div>;
});
// 父组件
function Parent() {
const childRef = useRef();
return (
<>
<Child ref={childRef} />
<button onClick={() => childRef.current.doSomething()}>
Trigger
</button>
</>
);
}






