微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在react-native-autocomplete-input组件中显示搜索图标

如何解决在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;

输入框如下所示。

enter image description here

我想要搜索输入框内左右的搜索图标。 有什么办法可以做到吗?

解决方法

以下是工作代码

//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,.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',alignItems: 'center',marginLeft: '5%',marginRight: '5%',backgroundColor: '#fff',searchIcon: {
    //padding: 10,paddingLeft: 10,clearIcon: {
    paddingRight: 10,});
export default App;

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

您的输出将类似于:

enter image description here

祝你有美好的一天!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。