[英]How to use ref in a functional component (expo camera)
I'm reacting my camera as a functional component but the documentation says我正在将我的相机作为一个功能组件做出反应,但文档说
To use methods that Camera exposes one has to create a component
ref
and invoke them using it.要使用 Camera 公开的方法,必须创建一个组件ref
并使用它调用它们。
but in react documentation it says that I can not use ref
in a functional component.但在反应文档中,它说我不能在功能组件中使用ref
。
if this the same thing as useRef
?如果这与useRef
相同? I'm trying to get the camera to take a picture and save it to my phones memory.我正在尝试让相机拍照并将其保存到我的手机内存中。
<Camera
style={{ flex: 1 }}
type={type}
useCamera2Api={true}
ratio={"16:9"}
//to take a picture
ref={ref => {
this.camera = ref;
}}
>
... ...
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}
onPress={() => async () => {
if (this.camera) {
let photo = await this.camera.takePictureAsync();
}}
>
<FontAwesome
name="camera"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
You can create one variable to assign with useRef
您可以创建一个变量来分配useRef
const cameraRef = useRef(null)
And then use cameraRef
in ref field like this:然后在 ref 字段中使用cameraRef
,如下所示:
<Camera
ref = {cameraRef}
/>
And then in your TouchableOpacity you will do it like this:然后在你的 TouchableOpacity 你会这样做:
if (cameraRef) {
const data = await cameraRef.current.takePictureAsync();
const [cameraRef, setCameraRef] = useState(null)
<Camera
ref={(ref) => {
setCameraRef(ref)
}}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.