React Native Alert 可以等待用户响应吗?
问题描述:
React native Alert 是否可以等待用户的响应(就像暂停应用程序一样)而不是弹出并继续执行以下逻辑?
Can React native Alert wait for user's response (just like pausing the app) instead of just popup and proceed the following logic?
我认为 js alert 只会暂停应用程序.
I think js alert will just pause the application.
答
您可以使用 Alert
执行以下操作:
Here's what you can do with Alert
:
你可以用false设置cancelable,这样用户不按按钮就不能关闭警报
You can set cancelable with false, so the user can't close the alert without pressing a button
您可以为每个按钮设置回调.
You can set a callback with each button.
你也可以用 Promise 包装 Alert,这样你就可以使用 async
Also you can wrap the Alert with Promise so you can use async
const AsyncAlert = () => {
return new Promise((resolve, reject) => {
Alert.alert(
'Title',
'Message',
[
{text: 'YES', onPress: () => resolve('YES') },
{text: 'NO', onPress: () => resolve('NO') }
],
{ cancelable: false }
)
})
}
// Then to use the method
const userResponse = await AsyncAlert()
// ...the rest of your code