本文介绍了如何在 React Native 中等待警报对话框的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的观察,Alert 对话框似乎建立在 React Native 应用程序之上.因此,每次调用它时它都会弹出,并且不会出现在 render 函数中.
问题是它不是异步任务,因此 Alert 之后的代码将继续执行,无论回调函数如何.

From my observation, the Alert dialog seems built on top of the React Native app.So it pops out everytime you call it, and doesn't to be in the render function.
The catch is it is not an async task so the code after Alert will continue to execute regardless the callback function.

下面的代码演示了 Alert 对话框不断弹出的情况,因为它一遍又一遍地读取相同的条形码.
(它是用 TypeScript 编写的.相信我的话,这是一个有效的片段.)

The code below demonstrates a situation where the Alert dialog keeps popping out because it reads the same barcode over and over again.
(It is written in TypeScript. Just take my word, this is a valid snippet.)

 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 的响应?

Is there a way to pause the JS code and await the response from Alert?

推荐答案

Alert 不会暂停代码.在这种情况下,JS 不是唯一的问题 - Camera 组件也会在本机后台继续运行,它会触发 onBarCodeRead 侦听器,无论警报是否存在与否.

Alert does not pause the code. In this case JS is not the only problem - the Camera component also keeps running in the background which is native and it will trigger the onBarCodeRead listener, regardless if the Alert is present or not.

您可以尝试在 _onBarCodeRead 开始时使用 .

You could try to stop the camera at the beginning on _onBarCodeRead with the stopPreview() method mentioned in the docs.

另请注意,react-native-camera 目前正在从 Camera (RCTCamera) 迁移到 RNCamera 并且在新的 RNCamera 中我没有看到 stopPreview() 方法.无论如何,一个简单的标志也可以完成这项工作.

Also note that react-native-camera is currently in a migration process from Camera (RCTCamera) to RNCamera and in the new RNCamera I don't see a stopPreview() method. Anyhow, a simple flag would also do the job.

这篇关于如何在 React Native 中等待警报对话框的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:23