React Native country-picker-modal选中后国旗不显示问题
解决react-native-country-picker-modal选中后国旗不显示问题
你的代码存在两个核心问题,导致选中国家后国旗无法展示:
- 初始状态
country被设为空字符串,但组件需要接收国家对象而非字符串类型的值 - 未给
CountryPicker组件传递selectedCountry属性,组件无法识别当前选中的国家
修改后的代码如下:
import { useState } from 'react'; import { View } from 'react-native'; import CountryPicker from 'react-native-country-picker-modal'; export const CountrySelect = () => { // 初始化为null,或设置默认国家(如{cca2: 'US'}) const [country, setCountry] = useState(null); return ( <View style={styles.container}> <CountryPicker withFilter withFlag withCountryNameButton withAlphaFilter withCallingCode withEmoji // 传入当前选中的国家对象 selectedCountry={country} onSelect={(selectedCountry) => setCountry(selectedCountry)} /> </View> ); };
额外说明
onSelect回调返回的是完整的国家对象(包含cca2、flag、name等字段),所以state需要存储对象类型的值- 如果需要默认选中某个国家,可以将初始state设为对应的国家对象,例如
useState({cca2: 'CN'})
内容的提问来源于stack exchange,提问作者med hedi ben salah
相关产品推荐
相关产品推荐

