RN-China-Region-Picker: 简易高效的React Native地区选择器
以下是一个简化的React组件代码示例,展示了如何创建一个省市区级联选择器:
import React, { useState } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
const RegionPicker = ({ regions }) => {
const [selectedProvince, setSelectedProvince] = useState(null);
const [selectedCity, setSelectedCity] = useState(null);
const [selectedArea, setSelectedArea] = useState(null);
const renderProvince = ({ item }) => (
<Text
style={selectedProvince === item.name ? styles.selectedText : styles.text}
onPress={() => {
setSelectedProvince(item.name);
setSelectedCity(null);
setSelectedArea(null);
}}
>
{item.name}
</Text>
);
const renderCity = ({ item }) => (
<Text
style={selectedCity === item.name ? styles.selectedText : styles.text}
onPress={() => {
setSelectedCity(item.name);
setSelectedArea(null);
}}
>
{item.name}
</Text>
);
const renderArea = ({ item }) => (
<Text style={selectedArea === item ? styles.selectedText : styles.text} onPress={() => setSelectedArea(item)}>
{item}
</Text>
);
const regionsForProvince = regions.find(province => province.name === selectedProvince);
const citiesForProvince = regionsForProvince ? regionsForProvince.cities : [];
const areasForCity = citiesForProvince.find(city => city.name === selectedCity)?.areas;
return (
<View style={styles.container}>
<FlatList
data={regions}
keyExtractor={item => item.name}
renderItem={renderProvince}
/>
{selectedProvince && (
<FlatList
data={citiesForProvince}
keyExtractor={item => item.name}
renderItem={renderCity}
/>
)}
{selectedCity && areasForCity && (
<FlatList
data={areasForCity}
keyExtractor={item => item}
renderItem={renderArea}
/>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
// 样式定义省略
},
text: {
// 样式定义省略
},
selectedText: {
// 样式定义省略
}
});
export default RegionPicker;
这个简化的例子展示了如何使用React Hooks(useState)来管理组件状态,以及如何使用FlatList组件来渲染省市区数据。代码简洁,易于理解和学习。
评论已关闭