根据我的观察,Alert对话框似乎建立在React Native应用程序之上.因此每次调用它时都会弹出,而不是在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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法暂停JS代码并等待响应Alert?
小智 5
React-native Alert不会停止执行其下面的代码。通过将其更改为异步功能,该功能可以解决对用户操作的承诺,将用作ASYNC-Alert。
const AsyncAlert = async () => new Promise((resolve) => {
Alert.alert(
'info',
'Message',
[
{
text: 'ok',
onPress: () => {
resolve('YES');
},
},
],
{ cancelable: false },
);
});
await AsyncAlert();Run Code Online (Sandbox Code Playgroud)
我刚刚发布了一个软件包,该软件包正是这样做的,并允许等待用户的选择。它与Expo兼容。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
原始答案:我为此功能向ReactNative进行了宣传:https : //github.com/facebook/react-native/pull/20312
| 归档时间: |
|
| 查看次数: |
5421 次 |
| 最近记录: |