React Native中props.cityName变化时清空setSelectedCountry及下拉框优化
React Native下拉框问题解决方案
一、props.cityname变化时清空选中城市
要实现当props.cityname(注:代码中传入的是props.cityNames,需保持参数名一致)变化时清空selectedCountry,只需添加useEffect监听该props的变化:
import React, {useRef, useState, useEffect} from 'react'; import { FlatList, Image, Text, TextInput, TouchableOpacity, View, } from 'react-native'; const Test = props => { const [search, setSearch] = useState(''); const [clicked, setClicked] = useState(false); const [data, setData] = useState(props.cityNames); const [selectedCountry, setSelectedCountry] = useState(''); const searchRef = useRef(); // 监听props.cityname变化,清空选中值及相关状态 useEffect(() => { setSelectedCountry(''); setSearch(''); setData(props.cityNames); }, [props.cityname]); // 若实际传入的props字段是cityNames,替换为props.cityNames const onSearch = search => { if (search !== '') { const tempData = data.filter(item => { return item.value.toLowerCase().indexOf(search.toLowerCase()) > -1; }); setData(tempData); } else { setData(props.cityNames); } }; const isFound = data.some(element => { if (element.value === selectedCountry) { return true; } return false; }); return ( <View> {/* 原有触发按钮代码不变 */} <TouchableOpacity style={{ paddingHorizontal: 16, paddingVertical: 20, borderRadius: 10, backgroundColor: '#F2F4F7', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }} onPress={() => { setClicked(!clicked); }}> <Text style={{fontWeight: '600'}}> {selectedCountry == '' ? 'Select Country' : selectedCountry} </Text> {clicked ? ( <Image source={require('./upload.png')} style={{width: 20, height: 20}} /> ) : ( <Image source={require('./dropdown.png')} style={{width: 20, height: 20}} /> )} </TouchableOpacity> {/* 下拉框部分修改如下 */} {clicked ? ( <View style={{ marginTop: 10, backgroundColor: '#F2F4F7', borderRadius: 10, paddingHorizontal: 0, paddingVertical: 0, borderColor: '#F2F4F7', maxHeight: 300, overflow: 'hidden', // 防止内容溢出容器 }}> <TextInput placeholder="Search.." value={search} ref={searchRef} onChangeText={txt => { onSearch(txt); setSearch(txt); }} style={{ width: '90%', alignSelf: 'center', borderWidth: 1, borderColor: 'white', borderRadius: 10, marginTop: 20, paddingLeft: 16, }} /> <FlatList nestedScrollEnabled data={data} style={{ flexGrow: 1 }} // 让列表占满剩余空间,支持滚动 keyExtractor={(item) => item.value} // 添加key提升性能 renderItem={({item, index}) => { return ( <TouchableOpacity style={{ width: '85%', alignSelf: 'center', paddingVertical: 16, justifyContent: 'center', }} onPress={() => { setSelectedCountry(item.value); setClicked(!clicked); onSearch(''); setSearch(''); }}> <Text style={{fontWeight: '600'}}>{item.value}</Text> </TouchableOpacity> ); }} /> </View> ) : null} </View> ); }; export default Test;
二、下拉框max-height优化说明
- 给下拉框容器添加
overflow: 'hidden',确保超出maxHeight的内容被裁剪,避免布局错乱。 - 给
FlatList设置flexGrow: 1,让列表在容器内自动占据剩余空间,当数据量超过容器高度时自动触发滚动。 - 添加
keyExtractor属性,符合React Native列表组件最佳实践,避免渲染警告。
内容的提问来源于stack exchange,提问作者Shiva Giri
相关产品推荐
相关产品推荐

