Skip to content

弹窗提示(Alert)

React Native 核心基础

在 React Native 应用中,弹窗提示是一种常见的用户交互方式,用于显示重要信息、获取用户确认或警告用户。本文将详细介绍 React Native 中的 Alert 组件的使用方法。

1. 基本使用

简单提示

jsx
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function SimpleAlertExample() {
  const showAlert = () => {
    Alert.alert('提示', '这是一个简单的弹窗提示');
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.button} onPress={showAlert}>
        <Text style={styles.buttonText}>显示弹窗</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

带按钮的弹窗

jsx
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function AlertWithButtonsExample() {
  const showAlert = () => {
    Alert.alert(
      '确认操作',
      '确定要执行此操作吗?',
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '确定',
          onPress: () => console.log('用户点击了确定'),
        },
      ],
      { cancelable: false }
    );
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.button} onPress={showAlert}>
        <Text style={styles.buttonText}>显示带按钮的弹窗</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

多个按钮的弹窗

jsx
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function MultiButtonAlertExample() {
  const showAlert = () => {
    Alert.alert(
      '选择操作',
      '请选择您要执行的操作',
      [
        {
          text: '操作一',
          onPress: () => console.log('用户选择了操作一'),
        },
        {
          text: '操作二',
          onPress: () => console.log('用户选择了操作二'),
        },
        {
          text: '取消',
          style: 'cancel',
        },
      ],
      { cancelable: true }
    );
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.button} onPress={showAlert}>
        <Text style={styles.buttonText}>显示多按钮弹窗</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

2. 高级用法

自定义按钮样式

jsx
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function CustomButtonAlertExample() {
  const showAlert = () => {
    Alert.alert(
      '删除确认',
      '确定要删除这条记录吗?此操作不可撤销。',
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '删除',
          style: 'destructive',
          onPress: () => console.log('用户确认删除'),
        },
      ],
      { cancelable: true }
    );
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.button} onPress={showAlert}>
        <Text style={styles.buttonText}>显示带危险按钮的弹窗</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

可取消的弹窗

jsx
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function CancelableAlertExample() {
  const [canceled, setCanceled] = useState(false);

  const showAlert = () => {
    setCanceled(false);
    Alert.alert(
      '可取消弹窗',
      '点击弹窗外部可以关闭此弹窗',
      [
        {
          text: '确定',
          onPress: () => console.log('用户点击了确定'),
        },
      ],
      { 
        cancelable: true,
        onDismiss: () => setCanceled(true)
      }
    );
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.button} onPress={showAlert}>
        <Text style={styles.buttonText}>显示可取消弹窗</Text>
      </TouchableOpacity>
      {canceled && (
        <Text style={styles.canceledText}>弹窗被取消了</Text>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
  canceledText: {
    marginTop: 20,
    fontSize: 16,
    color: '#666',
  },
});

动态内容弹窗

jsx
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function DynamicAlertExample() {
  const [name, setName] = useState('');

  const showAlert = () => {
    if (!name) {
      Alert.alert('错误', '请输入姓名');
      return;
    }

    Alert.alert(
      '欢迎',
      `你好,${name}!欢迎使用我们的应用。`,
      [
        {
          text: '确定',
          onPress: () => console.log('用户点击了确定'),
        },
      ]
    );
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        value={name}
        onChangeText={setName}
        placeholder="请输入姓名"
      />
      <TouchableOpacity style={styles.button} onPress={showAlert}>
        <Text style={styles.buttonText}>显示欢迎弹窗</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    padding: 10,
    borderRadius: 5,
    width: '100%',
    marginBottom: 20,
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

3. 实际应用场景

登录失败提示

jsx
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function LoginAlertExample() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = () => {
    if (!username || !password) {
      Alert.alert('错误', '请输入用户名和密码');
      return;
    }

    // 模拟登录失败
    setTimeout(() => {
      Alert.alert(
        '登录失败',
        '用户名或密码错误,请重试',
        [
          {
            text: '确定',
            onPress: () => console.log('用户点击了确定'),
          },
        ]
      );
    }, 1000);
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        value={username}
        onChangeText={setUsername}
        placeholder="请输入用户名"
        marginBottom={10}
      />
      <TextInput
        style={styles.input}
        value={password}
        onChangeText={setPassword}
        placeholder="请输入密码"
        secureTextEntry
        marginBottom={20}
      />
      <TouchableOpacity style={styles.button} onPress={handleLogin}>
        <Text style={styles.buttonText}>登录</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    padding: 10,
    borderRadius: 5,
    width: '100%',
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

操作成功提示

jsx
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function SuccessAlertExample() {
  const [count, setCount] = useState(0);

  const handleIncrement = () => {
    setCount(prevCount => prevCount + 1);
    Alert.alert(
      '操作成功',
      '计数已增加',
      [
        {
          text: '确定',
          onPress: () => console.log('用户点击了确定'),
        },
      ],
      { cancelable: true }
    );
  };

  return (
    <View style={styles.container}>
      <Text style={styles.count}>{count}</Text>
      <TouchableOpacity style={styles.button} onPress={handleIncrement}>
        <Text style={styles.buttonText}>增加计数</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  count: {
    fontSize: 36,
    marginBottom: 20,
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

网络错误提示

jsx
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';

export default function NetworkErrorAlertExample() {
  const simulateNetworkError = () => {
    // 模拟网络请求失败
    setTimeout(() => {
      Alert.alert(
        '网络错误',
        '无法连接到服务器,请检查网络连接后重试',
        [
          {
            text: '取消',
            style: 'cancel',
          },
          {
            text: '重试',
            onPress: () => console.log('用户点击了重试'),
          },
        ]
      );
    }, 1000);
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.button} onPress={simulateNetworkError}>
        <Text style={styles.buttonText}>模拟网络错误</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
});

4. 最佳实践

1. 保持简洁

弹窗内容应该简洁明了,避免过多的文字和复杂的操作。

2. 合理使用按钮

  • 对于确认操作,使用两个按钮(确认和取消)
  • 对于信息展示,使用一个按钮(确定)
  • 对于危险操作,使用带有 destructive 样式的按钮

3. 处理取消操作

当用户点击弹窗外部或返回按钮时,应该处理取消操作。

4. 避免过度使用

不要过度使用弹窗,这会影响用户体验。只在必要时使用弹窗。

5. 国际化支持

如果应用支持多语言,弹窗内容应该支持国际化。

5. 常见问题与解决方案

问题 1:弹窗不显示

问题:调用 Alert.alert() 后弹窗不显示。

解决方案

  • 检查参数是否正确
  • 确保在主线程中调用 Alert.alert()
  • 检查是否有其他代码阻止了弹窗显示

问题 2:弹窗按钮顺序不正确

问题:弹窗按钮的顺序与预期不符。

解决方案

  • 在 iOS 上,按钮顺序是从右到左
  • 在 Android 上,按钮顺序是从左到右
  • 为了保持一致性,可以将取消按钮放在最后

问题 3:弹窗内容过长

问题:弹窗内容过长,显示不完整。

解决方案

  • 保持弹窗内容简洁
  • 对于长内容,考虑使用 Modal 组件
  • 对于列表选择,考虑使用 ActionSheetIOS 或自定义组件

问题 4:弹窗样式不符合设计要求

问题:默认弹窗样式不符合应用的设计要求。

解决方案

  • 使用第三方弹窗库,如 react-native-modal
  • 自定义 Modal 组件
  • 对于 iOS,可以使用 ActionSheetIOS

6. 第三方库推荐

1. react-native-modal

功能丰富的模态框库,支持自定义样式和动画。

bash
npm install react-native-modal

2. react-native-dialog

用于创建自定义对话框的库。

bash
npm install react-native-dialog

3. @react-native-community/datetimepicker

用于日期和时间选择的弹窗。

bash
npm install @react-native-community/datetimepicker

7. 总结

Alert 组件是 React Native 中用于显示弹窗提示的重要组件。通过本文的学习,你应该掌握了以下内容:

  1. Alert 组件的基本使用方法
  2. 带按钮的弹窗实现
  3. 自定义按钮样式
  4. 可取消的弹窗
  5. 动态内容弹窗
  6. 实际应用场景
  7. 最佳实践和常见问题的解决方案

在实际开发中,合理使用 Alert 组件,可以为用户提供清晰、直观的交互反馈,提升应用的用户体验。

© 2026 编程马·菜鸟教程 版权所有