来自带有 FlatList 的 react-native-elements 的 SearchBar 只允许我一个一个地输入字符

SearchBar from react-native-elements with FlatList only allows me to type characters one by one

我在功能组件内的应用程序中使用来自 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>
    );
  } else {
    return (
      <View>
      <SafeAreaView>
        <FlatList
          data={institutions}
          renderItem={({ item }) => 
            <InstitutionItem 
              title={item.name} 
              image={require('../../../assets/hands.jpg')} 
              logo={require('../../../assets/institution.png')}
              location={item.address}
              phone={item.phone}
              email={item.email}
              navigation={navigation}
              id={item._id}
              />}
            keyExtractor={(item, index) => index.toString()}
            refreshing={refresh}
            onRefresh={() => onRefresh()}
            ListHeaderComponent={renderHeader}
        />
      </SafeAreaView>
      </View>
    );
  }
}

我试过你的代码,它似乎与 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 的 header 中或常量。阿布拉佐!