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

Javascript 如何访问函数组件中的类组件方法?,javascript,reactjs,react-hooks,filepond,Javascript,Reactjs,React Hooks,Filepond,我试图访问函数组件中的类组件方法。我已经读了好几个小时了,但我错过了一些东西 确切地说,我试图访问Filepond组件的addFiles方法 如文档中所述,我可以引用类组件: <FilePond ref={ref => this.pond = ref}/> 但我不能在函数中使用该方法,因为“this”不能在函数中使用 TypeError:无法设置未定义的属性“pond” 我认为useRef-hook可能会有所帮助,但它只适用于html元素 import React from

我试图访问函数组件中的类组件方法。我已经读了好几个小时了,但我错过了一些东西

确切地说,我试图访问Filepond组件的addFiles方法

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

<FilePond ref={ref => this.pond = ref}/>
但我不能在函数中使用该方法,因为“this”不能在函数中使用

TypeError:无法设置未定义的属性“pond”

我认为useRef-hook可能会有所帮助,但它只适用于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,但我认为它应该是这样的:

this.pond.addFiles();
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} />
   )
}

来源:

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

this.pond.addFiles();
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} />
   )
}

来源:

UseRef将创建一个ref。UseRef钩子是一个函数,它返回一个可变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} />
   )
}

UseRef将创建一个ref。UseRef钩子是一个函数,它返回一个可变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} />
   )
}

功能组件是否与类组件相关?Ie祖父母/父母/子女?为什么不将功能组件转换为类组件,因此,它类似于文档中描述的行为。功能组件是否与类组件相关?Ie祖父母/父母/子女?为什么不将功能组件转换为类组件,因此,它类似于文档中描述的行为。“非常感谢,它可以工作!”!我忘了包括。当前的。谢谢蒂姆这么快就解决了我的问题!“非常感谢,它很管用!我忘了包括。当前的。谢谢蒂姆这么快就解决了我的问题!