簡體   English   中英

無法使用 React Hooks 從父 function 訪問子 function

[英]Can't access child function from parent function with React Hooks

我需要使用 React Hooks 從父組件的子組件中調用 function。

我試圖讓這個問題適應我的用例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;

我究竟做錯了什么?

我認為這是你的問題

    childRef.current(childRef.childFunction())

childRef.current不是 function。 還首先運行childRef.childFunction() ,這也不是 function。

childRef.current.childFunction應該是 function,嘗試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) => {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM