【问题标题】:This.refs for functional components (useRef, createRef) | React nativeThis.refs 用于功能组件(useRef、createRef)|反应原生
【发布时间】:2020-02-05 07:58:43
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    对于功能组件,您可以使用下面的钩子 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>
     )
    
    }
    

    【讨论】:

    • 你不需要检查viewShotRef是不是undefined / null
    • 你可以访问viewShotRef当你进入屏幕时它总是undefined或者null
    • 我试过了,但它不适合我。以前,这有效: const viewShotRef: any = this.refs.viewShot; const uri = 等待 viewShotRef.capture();但现在我永远无法运行 capture()。我总是得到:TypeError:viewShot.capture 不是函数
    • 只需添加 viewShotRef && viewShotRef.current && viewShotRef.current.capture()
    • 你错过了当前的参考调用,只需解决 viewShotRef 并看看你得到了什么
    【解决方案2】:
    
    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>
       </>);
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 2021-08-09
      • 2019-08-04
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      相关资源
      最近更新 更多