gpt4 book ai didi

javascript - 如何访问功能组件中的类组件方法?

转载 作者:行者123 更新时间:2023-12-02 16:37:05 26 4
gpt4 key购买 nike

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

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

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

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

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

this.pond.addFiles();

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

TypeError: Cannot set property 'pond' of undefined

虽然 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 将创建一个引用。 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} />
)
}

关于javascript - 如何访问功能组件中的类组件方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62466645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com