【问题标题】:React Native: Searchbar disappears after typing one single letterReact Native:输入一个字母后搜索栏消失
【发布时间】:2020-04-10 07:41:49
【问题描述】:

在我的 React Native 项目中,我想创建一个可搜索的列表,如 this 文章中所示。

现在,当我从here 复制并粘贴代码时,一切正常。

但是我必须做一些修改才能在我的项目中使用它。例如,我不需要获取随机的虚拟数据来填充列表,但已经有了一个,它的结构要简单得多。此外,我想使用带有 Hooks 的函数组件而不是类组件。 (而且我在 SearchBar 中使用 Native Base 而不是 Native-Elements,但这似乎没有任何问题。)

所以我把上面提到的文章示例转换成一个函数组件,但是现在 SearchBar-Typing 坏了。

搜索栏现在只允许输入一个字母,然后键盘消失,您必须再次单击输入字段才能继续输入。我完全不知道我在这里做错了什么。我已经尝试使用useEffect() Hook,但没有成功。你能帮帮我吗?

这是动画问题:

这里是代码:

import React, {useEffect, useState} from 'react';
import {View, FlatList, ActivityIndicator, StyleSheet} from 'react-native';
import {Button, Header, Icon, Item, Input, Text} from 'native-base';

type Props = {};

const FlatListDemo: React.FC<Props> = ({}) => {
  const arrayholder = [
    {
      id: '1',
      name: 'Hopper',
      selected: false,
    },
    {
      id: '2',
      name: 'Dustin',
      selected: false,
    },
    {
      id: '3',
      name: 'Mike',
      selected: false,
    },
  ];
  const [data, setData] = useState(arrayholder);
  const [value, setValue] = useState('');

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: '86%',
          backgroundColor: '#CED0CE',
          marginLeft: '14%',
        }}
      />
    );
  };

  const textChangedFunction = text => {
    setValue(text);
  };

  useEffect(() => {
    searchFilterFunction(value);
  }, [value]);

  const searchFilterFunction = text => {
    setValue(text);

    const newData = arrayholder.filter(item => {
      const itemData = `${item.name.toUpperCase()}`;
      const textData = text.toUpperCase();

      return itemData.indexOf(textData) > -1;
    });
    setData(newData);
  };

  renderHeader = () => {
    return (
      <Header searchBar rounded>
        <Item>
          <Icon name="ios-search" />
          <Input
            placeholder="Type Here..."
            onChangeText={text => textChangedFunction(text)}
            value={value}
          />
        </Item>
      </Header>
    );
  };

  return (
    <View style={{flex: 1}}>
      <FlatList
        data={data}
        renderItem={({item}) => (
          <ListItem title={`${item.name}`} subtitle={item.id} />
        )}
        ItemSeparatorComponent={renderSeparator}
        ListHeaderComponent={renderHeader}
      />
    </View>
  );
};

export default FlatListDemo;

我们将不胜感激!

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    请将 Flatlist 更改为此

    {data.map((item, index) => {
        return  <Text style={ {padding: 10,}}>{item.name}</Text>;
    })}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 2014-07-15
      • 1970-01-01
      相关资源
      最近更新 更多