【问题标题】:Use Java AlertDialog in reat-native在 react-native 中使用 Java 警报对话框
【发布时间】:2021-08-06 23:57:41
【问题描述】:

我正在开发一个使用 NearbyConnection API 的 react-native 应用程序。 我不希望自动接受连接。 用户应该能够接受或拒绝连接。 我尝试了谷歌提出的代码(代码如下)

new AlertDialog.Builder(context)
      .setTitle("Accept connection to " + info.getEndpointName())
      .setMessage("Confirm the code matches on both devices: " + info.getAuthenticationDigits())
      .setPositiveButton(
          "Accept",
          (DialogInterface dialog, int which) ->
              // The user confirmed, so we can accept the connection.
              Nearby.getConnectionsClient(context)
                  .acceptConnection(endpointId, payloadCallback))
      .setNegativeButton(
          "Refuse",
          (DialogInterface dialog, int which) ->
              // The user canceled, so we should reject the connection.
              Nearby.getConnectionsClient(context).rejectConnection(endpointId))
      .setIcon(android.R.drawable.ic_dialog_alert)
      .show();

但它不起作用(应用程序在此级别崩溃)。 有没有办法重写此代码以与 reat-native 兼容? 或者是否可以执行一个JS函数并在Java中得到结果?

【问题讨论】:

    标签: android react-native android-alertdialog


    【解决方案1】:

    您只需在下面执行此操作即可在 react-native 中获得跨平台原生警报。只需从 react-native 导入 Alert

    import React, { useState } from "react";
    import { View, StyleSheet, Button, Alert } from "react-native";
    
    const App = () => {
      const createTwoButtonAlert = () =>
        Alert.alert(
          "Alert Title",
          "My Alert Msg",
          [
            {
              text: "Cancel",
              onPress: () => console.log("Cancel Pressed"),
              style: "cancel"
            },
            { text: "OK", onPress: () => console.log("OK Pressed") }
          ]
        );
    
      const createThreeButtonAlert = () =>
        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") }
          ]
        );
    
      return (
        <View style={styles.container}>
          <Button title={"2-Button Alert"} onPress={createTwoButtonAlert} />
          <Button title={"3-Button Alert"} onPress={createThreeButtonAlert} />
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: "space-around",
        alignItems: "center"
      }
    });
    
    export default App;
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多