React中如何将子组件的函数传递给父组件并调用
子组件函数传递给父组件并调用的实现方案
在React中,组件默认遵循父到子的单向数据流,要实现子组件将内部函数传递给父组件调用,以下是两种可靠的实现方式:
方案一:通过回调Props传递(推荐)
父组件定义一个回调函数作为props传给子组件,子组件在挂载时将自身的handleAbort函数通过该回调传递给父组件,父组件存储后即可调用。
完整代码示例
import { useState, useEffect } from 'react'; function Parent() { // 存储子组件传来的函数 const [childAbortFn, setChildAbortFn] = useState(null); // 接收子组件函数的回调 const receiveChildFunction = (fn) => { setChildAbortFn(fn); }; const triggerChildAbort = () => { // 调用前做非空判断,避免报错 if (childAbortFn) { childAbortFn(); } }; return ( <div> <button onClick={triggerChildAbort}>调用子组件handleAbort</button> {/* 将回调传入子组件 */} <Child sendFunctionToParent={receiveChildFunction} /> </div> ); } function Child({ sendFunctionToParent }) { const handleAbort = () => { console.log('hello'); }; // 组件挂载时传递函数给父组件 useEffect(() => { sendFunctionToParent(handleAbort); // 组件卸载时清空引用,避免内存泄漏 return () => sendFunctionToParent(null); }, [sendFunctionToParent]); return <div>子组件内容</div>; }
方案二:使用Ref获取子组件函数
通过useRef和useImperativeHandle,让父组件直接通过引用访问子组件暴露的函数。这种方式会打破单向数据流,仅在必要时使用。
完整代码示例
import { useRef, forwardRef, useImperativeHandle } from 'react'; function Parent() { const childComponentRef = useRef(null); const triggerChildAbort = () => { if (childComponentRef.current) { childComponentRef.current.handleAbort(); } }; return ( <div> <button onClick={triggerChildAbort}>调用子组件handleAbort</button> <Child ref={childComponentRef} /> </div> ); } // 用forwardRef包裹子组件,接收父组件传入的ref const Child = forwardRef((props, ref) => { const handleAbort = () => { console.log('hello'); }; // 自定义暴露给父组件的方法 useImperativeHandle(ref, () => ({ handleAbort })); return <div>子组件内容</div>; });
关键注意点
- 方案一符合React单向数据流设计,逻辑更易维护,优先选择。
- 无论哪种方案,调用子组件函数前都要做非空判断,避免出现
Cannot read property 'xxx' of null的错误。
内容的提问来源于stack exchange,提问作者seyan
相关产品推荐
相关产品推荐

