在 reactjs 中未从父组件调用子组件函数

时间:2021-06-28 20:37:08

标签: reactjs use-ref

我正在使用 reactjs 构建游戏。我有一个父组件,我正在尝试使用 ref 调用子组件中的方法,但它不起作用。有人可以帮助为什么吗? (在下面的例子中忽略大小写。)

function parent() {
    childRef = useRef()

    ...
    const someFunc = () => {
        childRef.current.childFunc()
    }
    ...
    return <Child ref={childRef} />
}

function Child() {
    ...
    const childFunc = () => {
        ... code ...
    }
    ...
}

错误:无法读取未定义的属性“childFunc”

1 个答案:

答案 0 :(得分:0)

useImperativeHandle

我相信应该是这样的:

function parent() {
    childRef = useRef()

    ...
    const someFunc = () => {
        childRef.current.childFunc()
    }
    ...
    return <Child ref={childRef} />
}

function Child(props, ref) {
    ...
    useImperativeHandle(ref, () => ({
      childFunc: () => {
        ... code ...
      }
    }));
    ...
}

Child = forwardRef(Child);