首页 > 解决方案 > 在 react-native-autocomplete-input 组件中显示搜索图标

问题描述

我正在使用该react-native-autocomplete-input包进行自动完成搜索。 https://www.npmjs.com/package/react-native-autocomplete-input 这是一个有效的模板代码:

//Example of React Native AutoComplete Input
//https://aboutreact.com/example-of-react-native-autocomplete-input/

//import React in our code
import React, {useState, useEffect} from 'react';

//import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

//import Autocomplete component
import Autocomplete from 'react-native-autocomplete-input';

const App = () => {
  const [films, setFilms] = useState([]);  // For the main data
  const [filteredFilms, setFilteredFilms] = useState([]); // Filtered data
  const [selectedValue, setSelectedValue] = useState({}); // selected data

  useEffect(() => {
    fetch('https://aboutreact.herokuapp.com/getpost.php?offset=1')
      .then((res) => res.json())
      .then((json) => {
        const {results: films} = json;
        setFilms(films);
        //setting the data in the films state
      })
      .catch((e) => {
        alert(e);
      });
  }, []);

  const findFilm = (query) => {
    //method called everytime when we change the value of the input
    if (query) {
      //making a case insensitive regular expression
      const regex = new RegExp(`${query.trim()}`, 'i');
      //setting the filtered film array according the query
      setFilteredFilms(
          films.filter((film) => film.title.search(regex) >= 0)
      );
    } else {
      //if the query is null then return blank
      setFilteredFilms([]);
    }
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <Autocomplete
          autoCapitalize="none"
          autoCorrect={false}
          containerStyle={styles.autocompleteContainer}
          //data to show in suggestion
          data={filteredFilms}
          //default value if you want to set something in input
          defaultValue={
            JSON.stringify(selectedValue) === '{}' ?
            '' :
            selectedValue.title
          }
          // onchange of the text changing the state of the query
          // which will trigger the findFilm method
          // to show the suggestions
          onChangeText={(text) => findFilm(text)}
          placeholder="Enter the film title"
          renderItem={({item}) => (
            //you can change the view you want to show in suggestions
            <TouchableOpacity
              onPress={() => {
                setSelectedValue(item);
                setFilteredFilms([]);
              }}>
              <Text style={styles.itemText}>
                  {item.title}
              </Text>
            </TouchableOpacity>
          )}
        />
        <View style={styles.descriptionContainer}>
          {films.length > 0 ? (
            <>
              <Text style={styles.infoText}>
                   Selected Data
              </Text>
              <Text style={styles.infoText}>
                {JSON.stringify(selectedValue)}
              </Text>
            </>
          ) : (
            <Text style={styles.infoText}>
                Enter The Film Title
            </Text>
          )}
        </View>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#F5FCFF',
    flex: 1,
    padding: 16,
    marginTop: 40,
  },
  autocompleteContainer: {
    backgroundColor: '#ffffff',
    borderWidth: 0,
  },
  descriptionContainer: {
    flex: 1,
    justifyContent: 'center',
  },
  itemText: {
    fontSize: 15,
    paddingTop: 5,
    paddingBottom: 5,
    margin: 2,
  },
  infoText: {
    textAlign: 'center',
    fontSize: 16,
  },
});
export default App;

输入框如下所示。 在此处输入图像描述 我想在搜索输入框的右侧/左侧有一个搜索图标。有什么办法可以做到这一点吗?

标签: react-nativereact-native-flatlist

解决方案


这是工作代码

//Example of React Native AutoComplete Input
//https://aboutreact.com/example-of-react-native-autocomplete-input/

//import React in our code
import React, {useState, useEffect} from 'react';
import AntDesign from 'react-native-vector-icons/AntDesign';

//import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

//import Autocomplete component
import Autocomplete from 'react-native-autocomplete-input';

const App = () => {
  const [films, setFilms] = useState([]);  // For the main data
  const [filteredFilms, setFilteredFilms] = useState([]); // Filtered data
  const [selectedValue, setSelectedValue] = useState({}); // selected data

  useEffect(() => {
    fetch('https://aboutreact.herokuapp.com/getpost.php?offset=1')
      .then((res) => res.json())
      .then((json) => {
        const {results: films} = json;
        setFilms(films);
        //setting the data in the films state
      })
      .catch((e) => {
        alert(e);
      });
  }, []);

  const findFilm = (query) => {
    //method called everytime when we change the value of the input
    if (query) {
      //making a case insensitive regular expression
      const regex = new RegExp(`${query.trim()}`, 'i');
      //setting the filtered film array according the query
      setFilteredFilms(
          films.filter((film) => film.title.search(regex) >= 0)
      );
    } else {
      //if the query is null then return blank
      setFilteredFilms([]);
    }
  };

  return (
    <View style={{flex: 1}}><View><Text>Hello Friend</Text></View>
      <View style={styles.container}>
        <View style={styles.searchSection}>
          <AntDesign
            name="search1"
            size={18}
            color="gray"
            style={styles.searchIcon}
          />
          <Autocomplete
            autoCapitalize="none"
            autoCorrect={false}
            containerStyle={styles.autocompleteContainer}
            inputContainerStyle={styles.inputContainer}
            //data to show in suggestion
            data={filteredFilms}
            //default value if you want to set something in input
            defaultValue={
              JSON.stringify(selectedValue) === '{}'
                ? ''
                : selectedValue.title + selectedValue.id
            }
            // onchange of the text changing the state of the query
            // which will trigger the findFilm method
            // to show the suggestions
            onChangeText={(text) => findFilm(text)}
            placeholder="Search doctors, specialities, symptoms"
            renderItem={({item}) => (
              //you can change the view you want to show in suggestions
              <View>
                <TouchableOpacity
                  onPress={() => {
                    setSelectedValue(item);
                    setFilteredFilms([]);
                  }}>
                  <Text style={styles.itemText}>{item.title + item.id}</Text>
                </TouchableOpacity>
              </View>
            )}
          />
          <AntDesign
            name="close"
            size={18}
            color="gray"
            style={styles.clearIcon}
          />
        </View>
        <View style={styles.descriptionContainer}>
          {films.length > 0 ? (
            <>
              <Text style={styles.infoText}>
                   Selected Data
              </Text>
              <Text style={styles.infoText}>
                {JSON.stringify(selectedValue)}
              </Text>
            </>
          ) : (
            <Text style={styles.infoText}>
                Enter The Film Title
            </Text>
          )}
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#F5FCFF',
    flex: 1,
    padding: 16,
    marginTop: 40,
  },
    autocompleteContainer: {
    backgroundColor: '#ffffff',
    borderWidth: 0,
    marginLeft: 10,
    marginRight: 10,
    //paddingLeft: 15,
  },
  inputContainer: {
    //minWidth: 300,
    //width: "90%",
    //height: 55,
    backgroundColor: 'transparent',
    //color: '#6C6363',
    //fontSize: 18,
    //fontFamily: 'Roboto',
    borderBottomWidth: 1,
    //borderBottomColor: 'rgba(108, 99, 99, .7)',
    borderColor: 'transparent',
  },
  descriptionContainer: {
    flex: 1,
    justifyContent: 'center',
  },
  itemText: {
    fontSize: 15,
    paddingTop: 5,
    paddingBottom: 5,
    margin: 2,
  },
  infoText: {
    textAlign: 'center',
    fontSize: 16,
  },

  // testing below
  searchSection: {
    flex: 1,
    height: 50,
    borderRadius: 10,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: '5%',
    marginRight: '5%',
    backgroundColor: '#fff',
  },
  searchIcon: {
    //padding: 10,
    paddingLeft: 10,
    backgroundColor: 'transparent',
  },
  clearIcon: {
    paddingRight: 10,
    backgroundColor: 'transparent',
  },

});
export default App;

npm install react-native-vector-icons对于AntDesign图标。我正在使用"react-native-vector-icons": "^7.1.0".

您的输出将如下所示:

在此处输入图像描述

祝你有美好的一天!!


推荐阅读