我正在尝试访问功能组件内的类组件方法。我已经看了几个小时了,但是我想念一些东西。
准确地说,我正在尝试访问Filepond组件的方法(addFiles)(https://pqina.nl/filepond/docs/patterns/frameworks/react/)
如文档中所读,我可以引用类组件:
<FilePond ref={ref => this.pond = ref}/>
然后我可以使用如下方法:
this.pond.addFiles();
但是我不能在我的Function中使用该方法,因为'this'不能在Function中使用。
TypeError:无法设置未定义的属性“ pond”
我虽然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将创建一个参考。useRef Hook是一个函数,它返回一个可变的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} />
)
}