在 React Native 中,Alert 是一个全局的 API,用于显示原生系统的对话框。与 Web 浏览器中的 alert() 函数类似,但它提供了更多的功能和更好的用户体验,因为它是基于原生系统的对话框,而不是基于 Web 的弹出框。
alert()
static alert(title, message?, buttons?, options?)
参数:
- title ------ 对话框的标题。传递字符串或空字符串将隐藏标题。
- message ------ 显示在对话框标题下方的可选消息。
- buttons ------ 包含按钮配置的可选阵列。
- options ------ Android 的可选警报配置。
import React, { useState } from 'react';
import { View, Button, Alert } from 'react-native';
const AlertExample = () => {
const showAlert = () => {
Alert.alert(
'Alert Title',
'My Alert Msg',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'OK',
onPress: () => console.log('OK Pressed'),
},
],
{ cancelable: false },
);
};
return (
<View style={{ paddingTop: 50 }}>
<Button title="Show Alert" onPress={showAlert} />
</View>
);
};
export default AlertExample;
prompt()
在 React Native 中,并没有内建的 prompt() 函数,因为 prompt() 是 Web API 的一部分,用于在浏览器中显示一个对话框,提示用户输入一些文本。然而,React Native 提供了不同的方式来获取用户输入,比如使用 组件和模态对话框(如 Modal 组件或者第三方库如 react-native-modal)来模拟 prompt() 的行为。
import React, { useState } from 'react';
import { View, Text, TextInput, Modal, TouchableOpacity, StyleSheet } from 'react-native';
const Prompt = ({ visible, onClose, onSubmit }) => {
const [inputValue, setInputValue] = useState('');
const handleSubmit = () => {
onSubmit(inputValue);
onClose();
};
const handleChangeText = (text) => {
setInputValue(text);
};
return (
<Modal
animationType="slide"
transparent={false}
visible={visible}
onRequestClose={onClose}
>
<View style={styles.modal}>
<View style={styles.content}>
<Text style={styles.title}>请输入文本:</Text>
<TextInput
style={styles.input}
onChangeText={handleChangeText}
value={inputValue}
autoFocus={true}
/>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={handleSubmit}>
<Text style={styles.buttonText}>确定</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={onClose}>
<Text style={styles.buttonText}>取消</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
);
};
const styles = StyleSheet.create({
// ... 定义你的样式
});
// 在你的主组件中使用 Prompt 组件
// 例如:
function App() {
const [isVisible, setIsVisible] = useState(false);
const [input, setInput] = useState('');
const showPrompt = () => {
setIsVisible(true);
};
const handleClose = () => {
setIsVisible(false);
};
const handleSubmit = (value) => {
setInput(value);
console.log('Submitted value:', value);
handleClose();
};
return (
<View>
<TouchableOpacity onPress={showPrompt}>
<Text>显示 Prompt</Text>
</TouchableOpacity>
<Prompt
visible={isVisible}
onClose={handleClose}
onSubmit={handleSubmit}
/>
{/* 显示提交的值或其他内容 */}
</View>
);
}
export default App;