react hook如何通信
React Hook 通信方法
React Hook 提供了多种方式实现组件间的通信,以下为常见方法:
useState + Props
父组件通过 useState 管理状态,子组件通过 props 接收数据和回调函数。
// 父组件
const Parent = () => {
const [count, setCount] = useState(0);
return <Child count={count} onIncrement={() => setCount(c => c + 1)} />;
};
// 子组件
const Child = ({ count, onIncrement }) => {
return <button onClick={onIncrement}>Count: {count}</button>;
};
useContext 通过 Context API 实现跨层级组件通信,适合全局状态共享。
const CountContext = createContext();
// 父组件
const Parent = () => {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={{ count, setCount }}>
<Child />
</CountContext.Provider>
);
};
// 子组件
const Child = () => {
const { count, setCount } = useContext(CountContext);
return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>;
};
useReducer + Context
复杂状态管理场景下,结合 useReducer 和 Context 实现状态逻辑集中处理。
const CountContext = createContext();
// 父组件
const reducer = (state, action) => {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
default: throw new Error();
}
};
const Parent = () => {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<CountContext.Provider value={{ state, dispatch }}>
<Child />
</CountContext.Provider>
);
};
// 子组件
const Child = () => {
const { state, dispatch } = useContext(CountContext);
return <button onClick={() => dispatch({ type: 'increment' })}>
Count: {state.count}
</button>;
};
自定义 Hook 封装共享逻辑为自定义 Hook,实现多组件复用相同状态逻辑。
const useCounter = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(c => c + 1);
return { count, increment };
};
// 组件A
const ComponentA = () => {
const { count, increment } = useCounter();
return <button onClick={increment}>A: {count}</button>;
};
// 组件B
const ComponentB = () => {
const { count, increment } = useCounter();
return <button onClick={increment}>B: {count}</button>;
};
第三方状态库 对于大型应用,可使用 Redux、Zustand 或 MobX 等库管理全局状态。
// 使用 Zustand 示例
import create from 'zustand';
const useStore = create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 }))
}));
// 组件
const Counter = () => {
const { count, increment } = useStore();
return <button onClick={increment}>Count: {count}</button>;
};
选择依据
- 父子组件简单通信:
useState + Props - 跨多层级组件:
useContext - 复杂状态逻辑:
useReducer + Context - 逻辑复用:自定义 Hook
- 大型应用:第三方状态库







