React Native实现搜索框功能

手把手教你如何在React Native中实现搜索功能,搜索图标使用的是react-native-vector-icons中的MaterialIcons,前提是已经安装了react-native-vector-icons,安装react-native-vector-icons参见:在React Native项目中使用react-native-vector-icons图标

代码:

import React, {useState} from 'react';
import {
  View,
  Text,
  ScrollView,
  TextInput,
  ActivityIndicator,
} from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import {DrawerParamList, TabParamList} from '../../../types/types';
import {CompositeNavigationProp} from '@react-navigation/native';
import {BottomTabNavigationProp} from '@react-navigation/bottom-tabs';
import {DrawerNavigationProp} from '@react-navigation/drawer';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';

// export type HomeScreenProps = RouterStackScreenProps<'HomeScreen'>;
export type HomeScreenProps = CompositeNavigationProp<
  BottomTabNavigationProp,
  DrawerNavigationProp
>;
const HomeScreen = ({route, navigation}: HomeScreenProps) => {
  const [query, setQuery] = useState(''); // 搜索内容
  const [loading, setLoading] = useState(true); // 是否在搜索中
  const [opacity, setOpacity] = useState(0); // 清空搜索内容时清空图标的透明度

  const fetchData = () => {
    setLoading(false);
    setOpacity(1);
    // TODO
    //  调用后端搜索接口,
    //  搜索结束要将state恢复初始状态
    // setLoading(true);
    // setOpacity(0);
  };

  return (
    
      {/*TODO*/}
      
        
          
           {
              setQuery(query);
            }}
            onSubmitEditing={() => {
              fetchData();
            }}
          />
          {/*  搜索时显示加载指示器*/}
          
        
      
    
  );
};

export default HomeScreen;

使用React Native提供的TextInput组件来实现搜索输入框功能,该组件的属性说明:

  • autoFocus:自动选中输入内容
  • clearButtonMode:显示清除输入内容图标,只有在iOS显示这个属性
  • returnKeyType:回车键输入时键盘最后一个键显示的文本内容,这里设置文本为”search“,只有在iOS显示这个属性
  • onSubmitEditing:搜索触发的回调函数,这里绑定fetchData方法,需要在这里个方法调用后端搜索接口获取搜索结果
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章