简体   繁体   English

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

[英]This.refs for functional components (useRef, createRef) | React native

I have used this.refs on a class component and now I am refactoring it to be a functional component.我在类组件上使用了 this.refs,现在我将它重构为一个功能组件。 I am using the ViewShot lib: https://github.com/gre/react-native-view-shot In the previous implementation it was used like the following:我正在使用 ViewShot 库: https : //github.com/gre/react-native-view-shot在之前的实现中,它的使用方式如下:

You have a QR image in your app and you want to send the image on social media so you wrap it in ViewShot:您的应用中有一个 QR 图像,并且您想在社交媒体上发送该图像,因此您将其包装在 ViewShot 中:

<ViewShot ref="viewShot">
<QRImage
     address={....}
     image={...}
 />
</ViewShot>

Then when you click on the share image it does the following:然后,当您单击共享图像时,它会执行以下操作:

    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}`);
    }
};

So we use the ref using the this.refs of the class.所以我们使用类的 this.refs 来使用 ref。 I want to do it for a functional component.我想为一个功能组件做这件事。 preferably using hooks.最好使用钩子。 I know that userRef exists but it didn't work for me.我知道 userRef 存在,但它对我不起作用。 I also tried using createRef but wasn't sure how to implement it correctly.我也尝试过使用 createRef 但不确定如何正确实现它。

for functional component you can use below hook React alredy providing useRef hook so you can use it对于功能组件,您可以在钩子下方使用 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>
 )

}

import React, { useRef } from 'react';
import { TouchableOpacity, Text } from 'react-native';
import ViewShot from "react-native-view-shot";
 
class imageComponent = () => {
  const viewShotRef =  useRef();

  const onSave = () => {
    viewShotRef.current.capture().then(uri => {
      console.log("do something with ", uri);
    });
  }

   return (<>
      <ViewShot ref={viewShotRef} options={{ format: "jpg", quality: 0.9 }}>
        <Text>...Something to rasterize...</Text>
      </ViewShot>
      <TouchableOpacity onPress{onSave}>....</TouchableOpacity>
   </>);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM