react如何通信
React 组件通信方式
父组件向子组件传递数据
通过 props 传递数据,子组件通过 this.props(类组件)或直接解构 props(函数组件)接收。
// 父组件
<ChildComponent message="Hello from parent" />
// 子组件(函数组件)
const ChildComponent = ({ message }) => <div>{message}</div>;
子组件向父组件传递数据
父组件通过 props 传递回调函数,子组件调用该函数并传递数据。
// 父组件
const handleChildData = (data) => console.log(data);
<ChildComponent onData={handleChildData} />
// 子组件
<button onClick={() => props.onData("Child data")}>Send</button>
兄弟组件通信
通过状态提升(Lifting State Up),将共享状态提升到共同的父组件中管理。
// 父组件
const [sharedState, setSharedState] = useState("");
<ChildA onUpdate={setSharedState} />
<ChildB value={sharedState} />
跨层级组件通信
使用 Context API 或状态管理库(如 Redux、MobX)。
// 创建 Context
const MyContext = React.createContext();
// 提供者组件
<MyContext.Provider value={value}>
<ChildComponent />
</MyContext.Provider>
// 消费者组件(函数组件)
const value = useContext(MyContext);
全局状态管理(Redux)
适用于复杂应用,通过 store 集中管理状态,组件通过 connect 或 useSelector 访问。
// 定义 action 和 reducer
const increment = () => ({ type: 'INCREMENT' });
// 组件中触发
dispatch(increment());
事件总线(Event Emitter)
通过自定义事件或第三方库(如 events)实现发布-订阅模式。
// 订阅事件
eventEmitter.on('event', (data) => {});
// 发布事件
eventEmitter.emit('event', data);
Ref 通信
通过 useRef 或 createRef 直接访问组件实例或 DOM 节点。
const ref = useRef();
<ChildComponent ref={ref} />
// 调用子组件方法
ref.current.doSomething();
URL 参数或路由状态
通过 react-router 的 useParams 或 useLocation 传递数据。
// 路由配置
<Route path="/user/:id" component={User} />
// 组件中获取
const { id } = useParams();
选择建议
- 简单父子通信:
props或回调函数。 - 跨层级或全局状态:
Context API或 Redux。 - 非父子关系且简单场景:事件总线。
- 需要直接操作子组件:
ref。







