React中如何从父函数式组件调用子函数式组件的内部方法
父组件调用子函数组件内部方法的实现方案
React 函数组件默认不会对外暴露内部的属性和方法,你需要配合 forwardRef 和 useImperativeHandle 两个官方 API 实现需求,因为你的场景涉及 App -> NavBar -> MyChildFunction 三层组件,需要把 ref 逐层向下传递。
1. 修改子组件 MyChildFunction
用 forwardRef 包裹组件接收父级传递的 ref,再通过 useImperativeHandle 把需要对外暴露的方法挂载到 ref 上:
import React, { forwardRef, useImperativeHandle } from 'react'; // forwardRef 用于接收父组件传递的ref const MyChildFunction = forwardRef((props, ref) => { // 替换成你实际调用的库的逻辑 const { Test, reset } = useYourTargetLibrary(); // 将需要对外暴露的方法注册到ref useImperativeHandle(ref, () => ({ handleReset })) function handleReset() { reset(); } return ( <div style={{textAlign: 'center'}}> <div style={{fontSize: '30px', color : 'white'}}> <span>{Test}</span>:<span>{Test}</span>:<span>{Test}</span> </div> </div> ); }) export default MyChildFunction;
2. 修改中间层 NavBar 组件
作为中间层需要转发 ref 给下层的 MyChildFunction:
import React, { forwardRef } from 'react'; import MyChildFunction from './MyChildFunction'; const NavBar = forwardRef((props, ref) => { return ( <div> <MyChildFunction ref={ref}/> </div> ) }) export default NavBar;
3. 修改 App 组件
创建 ref 绑定到 NavBar 上,直接通过 ref 调用子组件暴露的方法即可:
import React, { useRef, useState } from 'react'; import NavBar from "./components/NavBar"; function App() { const childRef = useRef(null); const [state, setState] = useState(); const changeUserState = (newState) => { alert(newState); // 调用子组件的reset方法,加可选链避免ref未初始化时报错 childRef.current?.handleReset(); setState(newState); }; return ( <> <NavBar ref={childRef}/> </> ); }
注意事项
- 同一个文件只能有一个
export default,你原代码中如果把 MyChildFunction 和 NavBar 写在同一个文件,需要调整为命名导出,或者拆分到不同的文件中 - 不要把函数定义写在 return 语句之后,否则函数永远不会被执行到
- 调用 ref 上的方法时加可选链
?.,可以避免组件还没挂载完成时报错
内容的提问来源于stack exchange,提问作者IntelligentCancer
相关产品推荐
相关产品推荐

