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. 事件总线(非推荐,但简单)

// mitt 库
import mitt from 'mitt'
const emitter = mitt()

// 组件 A
emitter.emit('event', data)

// 组件 B
emitter.on('event', (data) => { ... })

6. 全局状态管理(Redux/Zustand/Jotai)

// Zustand
const useStore = create((set) => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 }))
}))

// 任何组件
const count = useStore(state => state.count)

各方案对比

方案 适用场景 复杂度
props 父子 低
Context 跨层级共享 中
状态提升 兄弟 低
ref 父调子方法 中
全局状态 大型应用 高
事件总线 简单解耦 低

选择建议

同分类其他题目