我已经在类组件上使用过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}`);
}
};
所以我们使用 ref 使用 this.refs 的类。 我想为功能组件执行此操作。最好使用钩子。 我知道用户参考存在,但它对我不起作用。我也尝试使用createRef,但不确定如何正确实现它。
对于功能组件,你可以在下面使用 hook React alredy 提供 useRef hook,所以你可以使用它
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>
</>);
}