React 组件之间有哪些通信方式?
1. 父子通信(props)
function Parent() {
return <Child name="Tom" />
}
function Child({ name }) {
return <div>{name}</div>
}
function Parent() {
const [msg, setMsg] = useState('')
return <Child onSend={setMsg} />
}
function Child({ onSend }) {
return <button onClick={() => onSend('hello')}>Send</button>
}
2. Context(跨层级)
const ThemeContext = createContext('light')
function App() {
return (
<ThemeContext.Provider value="dark">
<Deeply />
</ThemeContext.Provider>
)
}
function Deeply() {
const theme = useContext(ThemeContext)
return <div>{theme}</div>
}
3. useRef + useImperativeHandle(父调子方法)
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
clear: () => setInput('')
}))
return <input ref={inputRef} />
})
function Parent() {
const childRef = useRef()
return <>
<Child ref={childRef} />
<button onClick={() => childRef.current.focus()}>Focus</button>
</>
}
4. 状态提升(兄弟通信)
function Parent() {
const [value, setValue] = useState('')
return (
<>
<A value={value} />
<B onChange={setValue} />
</>
)
}
5. 事件总线(非推荐,但简单)
import mitt from 'mitt'
const emitter = mitt()
emitter.emit('event', data)
emitter.on('event', (data) => { ... })
6. 全局状态管理(Redux/Zustand/Jotai)
const useStore = create((set) => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 }))
}))
const count = useStore(state => state.count)
各方案对比
| 方案 |
适用场景 |
复杂度 |
| props |
父子 |
低 |
| Context |
跨层级共享 |
中 |
| 状态提升 |
兄弟 |
低 |
| ref |
父调子方法 |
中 |
| 全局状态 |
大型应用 |
高 |
| 事件总线 |
简单解耦 |
低 |
选择建议
- 父子 → props
- 跨层级 → Context(适合低频更新)
- 全局状态 → Zustand / Jotai(比 Redux 更轻量)
- 复杂业务 → Redux Toolkit
同分类其他题目