首页 > 解决方案 > 如何在 react-native 中使用下拉列表制作搜索栏?

问题描述

我想创建一个带有 react-native 下拉列表的搜索栏,更像这张图片在此处输入图像描述

我知道有很多关于这些的库,这使我的任务变得容易,但我刚刚开始使用 react-native,所以据我所知,我想知道这些东西是如何制作的。

我遇到了有关如何使用实时搜索制作搜索栏并通过根据您的搜索过滤数据来更新平面列表的教程,但它们都没有涉及下拉列表。

基于搜索词更新我的平面列表的代码已经完成,我只需要以下拉列表的形式显示这个平面列表。

指向教程或示例代码的链接会很有帮助。

标签: react-nativereact-native-androidreact-native-flatlist

解决方案


检查下面我使用flatlistTextInput创建的示例。搜索项目时,项目以下拉列表的形式显示。我想这会对你有所帮助。

import React, { Component } from 'react';
import { View, Text, FlatList, TextInput, ListItem } from 'react-native';

class FlatListDropDown extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      value: '',
    };

    this.arrayNew = [
      { name: 'Robert' },
      { name: 'Bryan' },
      { name: 'Vicente' },
      { name: 'Tristan' },
      { name: 'Marie' },
      { name: 'Onni' },
      { name: 'sophie' },
      { name: 'Brad' },
      { name: 'Samual' },
      { name: 'Omur' },
      { name: 'Ower' },
      { name: 'Awery' },
      { name: 'Ann' },
      { name: 'Jhone' },
      { name: 'z' },
      { name: 'bb' },
      { name: 'cc' },
      { name: 'd' },
      { name: 'e' },
      { name: 'f' },
      { name: 'g' },
      { name: 'h' },
      { name: 'i' },
      { name: 'j' },
      { name: 'k' },
      { name: 'l' },
    ];
  }

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

  searchItems = text => {
    const newData = this.arrayNew.filter(item => {
      const itemData = `${item.name.toUpperCase()}`;
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      data: newData,
      value: text,
    });
  };

  renderHeader = () => {
    return (
      <TextInput
        style={{ height: 60, borderColor: '#000', borderWidth: 1 }}
        placeholder="   Type Here...Key word"
        onChangeText={text => this.searchItems(text)}
        value={this.state.value}
      />
    );
  };

  render() {
    return (
      <View
        style={{
          flex: 1,
          padding: 25,
          width: '98%',
          alignSelf: 'center',
          justifyContent: 'center',
        }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <Text style={{ padding: 10 }}>{item.name} </Text>
          )}
          keyExtractor={item => item.name}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
        />
      </View>
    );
  }
}

export default FlatListDropDown;

随意质疑


推荐阅读