根据我的观察,Alert对话框似乎构建在React Native应用程序之上. 因此每次调用它时都会弹出,而不是在渲染函数中. 问题是它不是异步任务,因此无论回调函数如何,Alert之后的代码都将继续执
因此每次调用它时都会弹出,而不是在渲染函数中.
问题是它不是异步任务,因此无论回调函数如何,Alert之后的代码都将继续执行.
下面的代码演示了一个警告对话框不断弹出的情况,因为它一遍又一遍地读取相同的条形码.
(它是用TypeScript编写的.只要听从我的话,这是一个有效的片段.)
import * as React from "react";
import Camera from "react-native-camera";
import { Alert } from "react-native";
export default class BarcodeScanSreen extends React.Component<any ,any> {
private _camera;
private _onBarCodeRead = e => {
if (e.type === "QR_CODE") {
Alert.alert(
"QRCode detected",
"Do you like to run the QRCode?",
[
{ text: "No", onPress: this._onNoPress },
{ text: "Yes", onPress: this._onYesPress }
],
{ cancelable: false }
);
}
};
private _onYesPress = () => { /* process the QRCode */ }
private _onNoPress = () => { /* close the alert dialog. */ }
render() {
return (
<Camera
onBarCodeRead={this._onBarCodeRead}
aspect={Camera.constants.Aspect.fill}
ref={ref => (this._camera = ref)}
>
{/* Some another somponents which on top of the camera preview... */}
</Camera>
);
}
}
有没有办法暂停JS代码并等待来自Alert的响应?
警报不会暂停代码.在这种情况下,JS不是唯一的问题 – Camera组件也会继续在后台运行,这是本机的,它将触发onBarCodeRead侦听器,无论是否存在Alert.您可以尝试使用docs中提到的stopPreview()方法在_onBarCodeRead的开头停止相机.
另请注意,react-native-camera目前处于从Camera(RCTCamera)到RNCamera的迁移过程中,在新的RNCamera中我没有看到stopPreview()方法.无论如何,一个简单的旗帜也可以完成这项工作.
