React Native 中的简单警报 - 按下时的功能

Simple Alert in React Native - function on press

在 React Native 中,我们可以选择使用警报在弹出窗口中通知用户。这些 'simple' 警报可以由以下内容组成:

Alert.alert('Hello world!')

它会生成一个带有消息、无标题和 "OK" 按钮的警报。

也可以制作2个或3个按钮的Alerts,组成如下(2个按钮示例):

Alert.alert(
  'Alert Title',
  'My Alert Msg',
  [
    {
      text: 'Ask me later', 
      onPress: () => console.log('Ask me later pressed')
    },
    {
      text: 'Cancel',
      onPress: () => console.log('Cancel Pressed'),
      style: 'cancel',
    },
    {
      text: 'OK', 
      onPress: () => console.log('OK Pressed')
    },
  ],
  {cancelable: false},
);

请注意,这里有按钮的 onPress 功能选项

我想知道的是,当按下 'OK' 时,我是否可以为第一种情况应用 onPress,但 [=14] 中没有示例(或任何细节!) =]

也许(还)不可能。谁能证实或否认?

您可以只用一个按钮创建一个 Alert。然后,您可以决定按 OK 时会发生什么。

https://facebook.github.io/react-native/docs/alert

iOS

On iOS you can specify any number of buttons. Each button can optionally specify a style, which is one of 'default', 'cancel' or 'destructive'.

Android

On Android at most three buttons can be specified. Android has a concept of a neutral, negative and a positive button:

  • If you specify one button, it will be the 'positive' one (such as 'OK')
  • Two buttons mean 'negative', 'positive' (such as 'Cancel', 'OK')
  • Three buttons mean 'neutral', 'negative', 'positive' (such as 'Later', 'Cancel', 'OK')

所以如果你只想要一个按钮,那么你可以这样做。

Alert.alert(
  'Alert Title',
  'My Alert Msg', // <- this part is optional, you can pass an empty string
  [
    {text: 'OK', onPress: () => console.log('OK Pressed')},
  ],
  {cancelable: false},
);

如果你使用 Alert.alert('Hello world!') 而没有传递任何选项,那么就没有办法定义当你按下 OK 时会发生什么,唯一的方法就是像我展示的那样做多于。如果你想让它在屏幕上看起来一样,那么只需为消息传递一个空字符串。标题和消息都可以是空字符串,但您可能不希望两者同时为空字符串。

如果不想使用标题,可以这样创建

Alert.alert(
     '',
     'Are you sure you want to delete?'+notificationId,  
     [
        {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
        {text: 'OK', onPress: () => console.log('OK Pressed')},
     ],
     { cancelable: false }
)