首页 > 解决方案 > nativebase 自动完成无法找到

问题描述

我是 React Native 的新手,我正在使用 NativeBase 构建我的演示应用程序。我无法使用 nativebase 创建自动完成搜索框。谁能帮我举个例子?我的要求: 1. 圆形搜索框 2. 单击后应显示取消按钮 3. 输入 2 个字母后,应为用户提供选择选项 4. 选择选项。

我在谷歌搜索。但是找不到任何满足我要求的东西。任何人都可以请帮忙。

标签: react-nativenative-base

解决方案


对于您的确切要求,您可以编写自己的代码。我试图编写自动完成功能。你可以在世博会签到。

这是 react-native 自动完成功能的基本代码。

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

export default class AutoCompleteBasics extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      textInputFocus: false,
      arrayList: ['Apple', 'Mango', 'Guava', 'Muskmelon', 'Watermelon', 'Orange', 'Sapota']
    };
  }

  componentDidMount() {
    this.updateDataWithKey();
  }

  updateDataWithKey() {
    const { arrayList } = this.state;
    const dataWithKey = arrayList.map(data => {
      return {'key': data}
    });
    this.setState({dataWithKey, filterData: dataWithKey});
  }

  changeText(text) {
    this.setState({text});
    const { dataWithKey } = this.state;
    if (text !== '') {
      let filterData = dataWithKey.filter(obj => {
        return obj.key.toLowerCase().indexOf(text.trim().toLowerCase()) > -1;
      });
      if (filterData.length === 0) {
        filterData = [{key: 'No Filter Data'}];
      }
      this.setState({filterData});
    } else {
      this.setState({filterData: dataWithKey});
    }
  }

  onListItemClicked(text) {
    this.setState({
      text,
      textInputFocus: false,
      filterData: [{key: text}]
    });
  }

  renderRow(item) {
    return (
      <TouchableOpacity
        onPress={() => this.onListItemClicked(item.key)}
        style={styles.listItem}
      >
        <Text style={styles.item}>{item.key}</Text>
      </TouchableOpacity>
    );
  }

  handleInputFocus() {
    this.setState({textInputFocus: true});
  }

  handleInputBlur() {
    this.setState({textInputFocus: false});
  }

  render() {
    const { filterData, textInputFocus } = this.state;
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.textInput}
          onFocus={() => this.handleInputFocus()}
          onBlur={() => this.handleInputBlur()}
          placeholder="Search & Select List!"
          onChangeText={(text) => this.changeText(text)}
          value={this.state.text}
        />
        {textInputFocus &&
          <FlatList
            data={filterData}
            renderItem={({item}) => this.renderRow(item)}
          />
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 8,
    paddingTop: 12
  },
  textInput: {
    height: 40,
    marginLeft: 5,
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

推荐阅读