无法使用Reaction钩子从父函数访问子函数 [英] Can't access child function from parent function with React Hooks

查看:17
本文介绍了无法使用Reaction钩子从父函数访问子函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我试图将这个问题应用于我的用例React 16:使用挂钩和功能组件时从父级调用子函数 但我一直收到错误

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;

我做错了什么?

推荐答案

我认为这是您的问题

    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) => {

这篇关于无法使用Reaction钩子从父函数访问子函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆