功能组件的 this.refs (useRef, createRef) | 反应原生

Con*_*top 1 reactjs react-native react-hooks

我在类组件上使用了 this.refs,现在我将它重构为一个功能组件。我正在使用 ViewShot 库:https : //github.com/gre/react-native-view-shot 在之前的实现中,它的使用方式如下:

您的应用中有一个 QR 图像,并且您想在社交媒体上发送该图像,因此您将其包装在 ViewShot 中:

<ViewShot ref="viewShot">
<QRImage
     address={....}
     image={...}
 />
</ViewShot>
Run Code Online (Sandbox Code Playgroud)

然后,当您单击共享图像时,它会执行以下操作:

    onQRImagePress = async (address: string) => {
    const viewShotRef: any = this.refs.viewShot;
    try {
        const uri = await viewShotRef.capture();
        const options: Options = {
            url: "file://" + uri,
            title: `address: ${address}`,
        };
        await Share.open(options);
    }
    catch (e) {
        console.log(`Could not screenshot the QR or share it due to: ${e}`);
    }
};
Run Code Online (Sandbox Code Playgroud)

所以我们使用类的 this.refs 来使用 ref。我想为一个功能组件做这件事。最好使用钩子。我知道 userRef 存在,但它对我不起作用。我也尝试过使用 createRef 但不确定如何正确实现它。

May*_*dav 6

对于功能组件,您可以在钩子下方使用 React 已经提供 useRef 钩子,以便您可以使用它

import React, { useRef } from 'react';
import ViewShot from "react-native-view-shot";

const Mycomponent = () =>{
 const viewShotRef =  useRef();
 // Access viewShotref 
  console.log(viewShotRef && viewShotRef.current)

 return (
     <View> 
        <ViewShot ref={viewShotRef} > {...children} </ViewShot>
     </View>
 )

}
Run Code Online (Sandbox Code Playgroud)