打开键盘时可以看到react-native-autocomplete-input

时间:2018-04-24 11:40:48

标签: react-native

我使用react-native-autocomplete-input组件,屏幕底部的 ,但我不知道如何在打开键盘时显示结果列表。我尝试使用ScrollViewreact-native-keyboard-spacer组件,但结果列表位于键盘后面。

import React, { Component } from 'react';
import {
  View,
  ScrollView,
  Platform,
  TouchableOpacity,
  Text,
} from 'react-native';
import styles from './styles';
import KeyboardSpacer from 'react-native-keyboard-spacer';
import Autocomplete from 'react-native-autocomplete-input';

const API = 'https://swapi.co/api';

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

    this.state = {
      query: '',
    };
  }

  componentDidMount() {
    fetch(`${API}/films/`)
      .then(res => res.json())
      .then((json) => {
        const { results: films } = json;
        this.setState({ films });
      });
  }

  findFilm(query) {
    if (query === '') {
      return [];
    }

    const { films } = this.state;
    const regex = new RegExp(`${query.trim()}`, 'i');
    return films.filter(film => film.title.search(regex) >= 0);
  }

  render() {
    const { query } = this.state;
    const films = this.findFilm(query);
    const comp = (a, b) => a.toLowerCase().trim() === b.toLowerCase().trim();

    return (
      <View style={styles.container}>
        <ScrollView style={styles.scrollView}>
          <Autocomplete
            autoCapitalize="none"
            autoCorrect={false}
            containerStyle={styles.autocompleteContainer}
            data={films.length === 1 && comp(query, films[0].title) ? [] : films}
            defaultValue={query}
            onChangeText={text => this.setState({ query: text })}
            placeholder="Enter Star Wars film title"
            renderItem={({ title, release_date }) => (
              <TouchableOpacity onPress={() => this.setState({ query: title })}>
                <Text style={styles.itemText}>
                  {title} ({release_date.split('-')[0]})
                </Text>
              </TouchableOpacity>
            )}
          />
        </ScrollView>
        {Platform.OS === 'ios' ? <KeyboardSpacer /> : null}
      </View>
    );
  }
}

export default Container;

export default styles = StyleSheet.create({
  container: {
    flex: 1,
    fontFamily: 'proxima_nova_regular',
    alignSelf: 'stretch',
  },
  scrollView: {
    alignSelf: 'stretch',
    flex: 1,
  },
  autocompleteContainer: {
    marginLeft: 10,
    marginRight: 10,
    marginTop: 400,
  },
  itemText: {
    fontSize: 15,
    margin: 2,
  },
});

1 个答案:

答案 0 :(得分:2)

Considering your case, you would need react-native-keyboard-aware-scroll-view

Although React Native has done a good job in implementing KeyboardAvoidingView, but it has many issues as mentioned here, particularly in a ScrollView, where it makes an extra slack on the bottom

And since the list items content can be dynamic, therefore it is necessary to wrap them inside a ScrollView.

Here are the changes that you can do in your code.

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

<KeyboardAwareScrollView
    innerRef={ref => this.scrollView = ref} //... Access the ref for any other functions here
    contentContainerStyle={{flex: 1}}>
    <Autocomplete
        onFocus={() => {this.scrollView.props.scrollToEnd({animated: true})}} // ... Scroll To End on TextInput focus
        autoCapitalize="none"
        autoCorrect={false}
        containerStyle={styles.autocompleteContainer}
        data={films.length === 1 && comp(query, films[0].title) ? [] : films}
        defaultValue={query}
        onChangeText={text => this.setState({ query: text })}
        placeholder="Enter Star Wars film title"
        renderItem={({ title, release_date }) => (
            <TouchableOpacity onPress={() => this.setState({ query: title })}>
                <Text style={styles.itemText}>
                    {title} ({release_date.split('-')[0]})
                </Text>
            </TouchableOpacity>
        )}
    />    
</KeyboardAwareScrollView>