如何访问函数组件中的 class 组件方法?

How can I access a class component method in a function component?

我正在尝试访问功能组件内的 class 组件方法。我已经阅读了几个小时,但我遗漏了一些东西。

准确地说,我正在尝试访问 Filepond 组件 (https://pqina.nl/filepond/docs/patterns/frameworks/react/)

的方法 (addFiles)

如文档中所述,我可以引用 class 组件:

<FilePond ref={ref => this.pond = ref}/>

然后我可以使用这样的方法:

this.pond.addFiles();

但我不能在我的函数中使用该方法,因为 'this' 不能在函数中使用。

TypeError: Cannot set property 'pond' of undefined

虽然 useRef 钩子可以提供帮助,但它只适用于 html 个元素。

import React from 'react';
import { FilePond } from "react-filepond";

const Example = () => {

   //How can I use this.pond.addFiles() here?

   return(
      <FilePond ref={ref => this.pond = ref} />
   )
}

感谢您的帮助。

我不经常使用 useRef,但我认为它应该是这样的:

import React from 'react';
import { FilePond } from "react-filepond";

const Example = () => {
   const filePondRef = useRef(null);
   // you should be able to use filePondRef (filePondRef.current) instead of "this.pond"

   return(
      <FilePond ref={filePondRef} />
   )
}

来源:https://reactjs.org/docs/hooks-reference.html#useref

UseRef 将创建一个引用。 useRef Hook 是一个 returns 可变 ref 对象的函数,其 .current 属性 被初始化为传递的参数 (initialValue)。返回的对象将在组件的整个生命周期内持续存在。

const refContainer = useRef(initialValue);

您可以使用此代码

import React, { useRef } from 'react';
import { FilePond } from "react-filepond";

const Example = () => {
  const file = useRef(null);

   // Use file.current.addFiles() instead of this.pond.addFiles();

   return(
      <FilePond ref={file} />
   )
}