glownight

返回

满分答案#

React 父子组件通信主要有四种核心方式:

  1. 父传子:通过 props 直接传递数据;
  2. 子传父:父组件通过 props 传递回调函数,子组件调用并传参;
  3. 父调用子组件方法/获取DOM:使用 useRef + forwardRef,配合 useImperativeHandle 控制暴露内容;
  4. 跨层级父子通信:使用 Context API 避免 props 逐层透传。 兄弟组件通信则以父组件为中间媒介进行转发。

一、最基础、最常用(90% 场景)#

1. 父 → 子:props 传值#

// 父
<Child name="小明" age={18} />

// 子
function Child({ name, age }) {
  return <div>{name}</div>
}
jsx

2. 子 → 父:props 传回调函数#

// 父
const handleMsg = (msg) => console.log(msg)
<Child onSend={handleMsg} />

// 子
function Child({ onSend }) {
  return <button onClick={() => onSend("来自子组件")}>发送</button>
}
jsx

二、进阶用法(ref 相关)#

3. 父获取子实例 / 调用子方法#

  • useRef + forwardRef
// 父
const childRef = useRef(null)
const callChild = () => childRef.current.sayHi()

<Child ref={childRef} />

// 子
const Child = forwardRef((props, ref) => {
  const sayHi = () => alert("hello")
  return <div>子组件</div>
})
jsx

4. 子可控暴露方法:useImperativeHandle#

useImperativeHandle(ref, () => ({
  sayHi: () => alert("hello")
}))
jsx

三、跨层级通信#

5. Context API(爷孙/深层组件)#

const MyContext = createContext()

// 父
<MyContext.Provider value={数据}>
  <Child />
</MyContext.Provider>

// 后代组件
const data = useContext(MyContext)
jsx

四、兄弟组件通信#

  • 兄弟A → 父 → 兄弟B
  • 本质还是:props + 回调函数
react父子组件通信有哪些方式?
作者 glownight
发布于 2026年1月25日