【问题标题】:Can't access child function from parent function with React Hooks无法使用 React Hooks 从父函数访问子函数
【发布时间】:2020-06-13 00:09:13
【问题描述】:

我需要使用 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;

我做错了什么?

【问题讨论】:

  • 有趣,不知道这个钩子。但是来自文档imperative code using refs should be avoided in most cases。为什么不将状态提升到父级。还是使用 redux 或上下文挂钩在组件之间传递值和函数?
  • childRef.current(childRef.childFunction()) - 这是故意的吗?你不应该直接打电话给childRef.current.childFunction()吗?
  • 我想这样做的原因是我有一个子组件,它使用来自上下文的数据,并且也将数据作为输入,但是当上下文为时,上下文不会在子组件中刷新从父级重置 - 但用例非常特殊
  • 我尝试了 childRef.current(childRef.childFunction()) 和 childRef.current.childFunction() - 都对我产生了相同的错误。我想我使用了第一个,因为我正在调整示例中的函数,并且他们在一组 refs 上使用了 forEach

标签: reactjs parent-child


【解决方案1】:

我认为这是你的问题

    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);

在此示例中,呈现&lt;FancyInput ref={inputRef} /&gt; 的父组件将能够调用inputRef.current.focus()

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

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

应该是

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

【讨论】:

  • 我还混淆了 refs 和 props。 ref 不是道具,所以我不得不提出 Ref(({}, ref) => { etc...
  • 谢谢,为未来的观众更新了答案。
  • 我有一个关于父母如何能够调用 inputRef.current.focus() 的问题?你会怎么做?
  • 我不再使用这种方法。如果我需要在我的孩子身上运行一些东西,我要么修改一个入站的道具,要么做一些事情来让 useEffect 运行。我认为这是一种反模式。
猜你喜欢
  • 2022-12-15
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多