使用React Native Modal Picker:打造优雅的移动端选择器体验
import React, { useState } from 'react';
import { View, Text, Modal, Pressable, StyleSheet } from 'react-native';
import RNPickerSelect from 'react-native-picker-select';
const ModalPickerExample = () => {
const [isModalVisible, setIsModalVisible] = useState(false);
const [selectedValue, setSelectedValue] = useState(null);
const showModal = () => setIsModalVisible(true);
const hideModal = () => setIsModalVisible(false);
return (
<View>
<Pressable onPress={showModal}>
<Text style={styles.pickerText}>{selectedValue || '选择一项'}</Text>
</Pressable>
<Modal animationType="slide" transparent={true} visible={isModalVisible} onRequestClose={hideModal}>
<View style={styles.modalView}>
<RNPickerSelect
onValueChange={value => setSelectedValue(value)}
items={[
{ label: '选项一', value: 'one' },
{ label: '选项二', value: 'two' },
{ label: '选项三', value: 'three' },
]}
/>
<Pressable style={styles.button} onPress={hideModal}>
<Text>确认</Text>
</Pressable>
</View>
</Modal>
</View>
);
};
const styles = StyleSheet.create({
pickerText: {
padding: 10,
backgroundColor: '#FFFFFF',
},
modalView: {
margin: 10,
padding: 20,
backgroundColor: 'white',
borderRadius: 4,
alignItems: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 5,
},
button: {
padding: 10,
backgroundColor: '#007BFF',
marginTop: 10,
borderRadius: 5,
alignItems: 'center',
},
});
export default ModalPickerExample;
这段代码使用React Native和RNPickerSelect库创建了一个简单的模态选择器组件。用户点击一个可按压的文本元素,会弹出一个Modal,其中包含了一个可供用户选择的RNPickerSelect组件。用户选择一项后,选择的值会显示在按压文本上,并且Modal会关闭。这个例子展示了如何使用React Hooks和React Native组件来创建一个响应式且易于维护的用户界面。
评论已关闭