想要在 React Hooks 父组件中调用子组件的某个方法,可以通过使用 useRef 钩子和 forwardRef 方法来实现此功能。下面是一些简单的示例代码
子组件
子组件中,需要使用 forwardRef 方法将子组件向父组件暴露出一个 ref 属性,从而在父组件中可以获取子组件的引用
const ChildComponent = React.forwardRef((props, ref) => { const childMethod = () => { // 处理逻辑 }; // 将子组件中需要调用的方法绑定到 ref React.useImperativeHandle(ref, () => ({ childMethod })); return ( // 子组件渲染代码 ); });
父组件
在父组件中,需要使用 useRef 钩子来创建一个 ref 对象,并将其传递给子组件的 ref 属性。这样,就可以通过这个 ref 对象来访问子组件的方法了
const ParentComponent = () => { const childRef = useRef(null); const handleChildMethod = () => { // 调用子组件中需要执行的方法 childRef.current.childMethod(); }; return ( <div> <ChildComponent ref={childRef} /> <button onClick={handleChildMethod}>调用子组件方法</button> </div> ); };
在上面的代码中,当用户单击“调用子组件方法”按钮时,会调用父组件中的 handleChildMethod 方法,该方法使用 childRef.current.childMethod() 语句来调用子组件中的 childMethod 方法