首页 > 解决方案 > 无法使用 React Hooks 从父函数访问子函数

问题描述

我需要使用 React Hooks 从父组件调用子组件中的函数。

我试图让这个问题适应我的用例React 16: Call children's function from parent when using hooks and functional component 但我一直收到错误

TypeError: childRef.childFunction is not a function

我的父组件是这样的:

import React, { useRef, useEffect } from 'react';
import Child from './child'

function Parent() {
    const parentRef = useRef()
    const childRef = useRef()

    const callChildFunction = () => {
        childRef.current(childRef.childFunction())
    }

    useEffect(() => {
        if (parentRef && childRef) {
            callChildFunction();
        }
    }, [parentRef, childRef])

    return (
        <div ref={parentRef} className="parentContainer">
            PARENT
            <Child ref={childRef}/>
        </div>
    );
}

export default Parent;

我的子组件是这样的:

import React, { forwardRef, useImperativeHandle } from 'react';

const Child = forwardRef(({ref}) => {
    useImperativeHandle(ref, () => ({
        childFunction() {
            console.log("CHILD FUNCTION")
        }
      })); 

    return (
        <div className="childContainer">
            CHILD
        </div>
    );
})

export default Child;

我究竟做错了什么?

标签: reactjsparent-child

解决方案


我认为这是你的问题

    childRef.current(childRef.childFunction())

childRef.current不是函数。也childRef.childFunction()首先运行,这也不是一个函数。

childRef.current.childFunction应该是一个函数,尝试childRef.current.childFunction()而不是childRef.current(childRef.childFunction())


从文档中useImperativeHandle查看以下内容的用法inputRef.current.focus()

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);

在此示例中,渲染的父组件<FancyInput ref={inputRef} />将能够调用inputRef.current.focus().

根据未来访问者的评论进行编辑:

const Child = forwardRef(({ref}) => {

应该

const child = forwardRef(({}, ref) => {

推荐阅读