从我的观察来看,Alert
对话框似乎建立在React之上。所以每次调用它时都会弹出,而不是在render
函数中。
问题是它不是异步任务,所以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
的响应?
发布于 2018-02-15 07:47:13
警报不会暂停代码。在这种情况下,JS不是唯一的问题-- Camera
组件也一直在本机背景中运行,它将触发onBarCodeRead
侦听器,不管警报是否存在。
您可以尝试用_onBarCodeRead
中提到的stopPreview()
方法在文档开始时停止照相机。
还请注意,react-native-camera
目前正处于从Camera
(RCTCamera
)到RNCamera
的迁移过程中,在新的RNCamera
中,我没有看到stopPreview()
方法。无论如何,一个简单的标志也可以完成这项工作。
发布于 2018-10-25 12:20:50
反应-本机警报不会停止执行下面的代码。通过将其更改为异步函数来解决对用户的承诺,操作将以Alert的形式工作。
const AsyncAlert = async () => new Promise((resolve) => {
Alert.alert(
'info',
'Message',
[
{
text: 'ok',
onPress: () => {
resolve('YES');
},
},
],
{ cancelable: false },
);
});
await AsyncAlert();
发布于 2018-11-13 06:56:39
我刚刚发布了一个包,它确实做到了这一点,并允许等待用户的选择。它与世博会兼容。
import AlertAsync from "react-native-alert-async";
const myAction = async () => {
const choice = await AlertAsync(
'Title',
'Message',
[
{text: 'Yes', onPress: () => 'yes'},
{text: 'No', onPress: () => Promise.resolve('no')},
],
{
cancelable: true,
onDismiss: () => 'no',
},
);
if (choice === 'yes') {
doSomething();
}
else {
doSomethingElse();
}
}
最初的回答:,我已经为ReactNative做了一个公关,其功能是:https://github.com/facebook/react-native/pull/20312
https://stackoverflow.com/questions/48809762
复制相似问题