我在功能组件内的应用程序中使用来自 react-native-elements 的 SearchBar。但是有一个问题我无法解决:我只能一个一个地输入字符。我不能连续在我的栏中写我的文字然后搜索。相反,我必须一个一个地输入每个字符才能找到一个特定的词。这是我的代码:export default function InstitutionsScreen({navigation}) { const [institutions, setInstitutions] = useState(''); const [refresh, setRefresh] = useState(false); const [fullData, setFullData] = useState([]); const [value, setValue] = useState(''); useEffect(() => { if(!institutions) { setRefresh(false); getInstitutions(); } }, []); const contains = (institutionName, query) => { if (institutionName.includes(query)) { return true } return false } const handleSearch = text => { setValue(text); const formattedQuery = text.toLowerCase() console.log("flaco me diste " + formattedQuery) const data = filter(fullData, inst => { return contains(inst.name.toLowerCase(), formattedQuery) }) setInstitutions(data); } const onRefresh = () => { setRefresh(true); getInstitutions(); }; const renderHeader = () => ( <View > <SearchBar lightTheme clearIcon onChangeText={(text) => handleSearch(text)} value={value} placeholder='Buscar...' /> </View> ) if (!institutions || refresh) { return ( <ScrollView contentContainerStyle={{alignItems: "center", flex: 1, justifyContent: 'center'}}> <Spinner isVisible={true} size={100} type={'Pulse'} color={'#013773'}/> </ScrollView> ); }
1 回答
慕娘9325324
TA贡献1783条经验 获得超4个赞
我试过你的代码,它似乎SearchBar与FlatList. 您遇到的问题是,由于某种原因,您正在失去输入焦点,因为您正在将其“注入”SearchBar到FlatList. 所以我所做的就是将权利SearchBar放入代码中,如下所示:
<FlatList
data={institutions}
keyExtractor={(item, index) => index.toString()}
refreshing={refresh}
onRefresh={() => onRefresh()}
ListHeaderComponent={
<SearchBar
lightTheme
clearIcon
onChangeText={handleSearch}
value={value}
placeholder='Buscar...' />
}
/>
它奏效了,您现在可以继续写作而不会失去焦点。FlatList这不是一个糟糕的解决方案,它是一个简单的解决方案,但如果这不是您喜欢的,您应该尝试找到如何将任何组件插入函数或 const 的标头中。
添加回答
举报
0/150
提交
取消