React native 如何在react native中实现搜索功能

React native 如何在react native中实现搜索功能,react-native,React Native,这是git hub的一个参考,并使用此代码使react native中的searh函数与此示例相同? 但我想在用户输入后创建一个serach函数,然后它应该 import React, { Component } from 'react'; import { View, Text, FlatList, ActivityIndicator } from 'react-native'; import { ListItem, SearchBar } from 'react-native-element

这是git hub的一个参考,并使用此代码使react native中的searh函数与此示例相同? 但我想在用户输入后创建一个serach函数,然后它应该

import React, { Component } from 'react';
import { View, Text, FlatList, ActivityIndicator } from 'react-native';
import { ListItem, SearchBar } from 'react-native-elements';

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

    this.state = {
      loading: false,
      data: [],
      error: null,
    };

    this.arrayholder = [];
  }

  componentDidMount() {
    this.makeRemoteRequest();
  }

  makeRemoteRequest = () => {
    const url = `https://www.achhamall.com/staging-achhamall.com/index.php?route=webservices/api&method=appGetCategoryDetails`;
    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: res.products,
          error: res.error || null,
          loading: false,
        });
        this.arrayholder = res.products;
        console.log(res.products)
      })
      .catch(error => {
        this.setState({ error, loading: false });
      });
  };

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: '86%',
          backgroundColor: '#CED0CE',
          marginLeft: '14%',
        }}
      />
    );
  };

  searchFilterFunction = text => {
    this.setState({
      value: text,
    });

    const newData = this.arrayholder.filter(item => {
      const itemData = `${item.name.toUpperCase()} ${item.name.toUpperCase()}`;
      const textData = text.toUpperCase();

      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      data: newData,
    });
  };

  renderHeader = () => {
    return (
      <SearchBar
        placeholder="Type Here..."
        lightTheme
        round
        onChangeText={text => this.searchFilterFunction(text)}
        autoCorrect={false}
        value={this.state.value}
      />
    );
  };

  render() {
    if (this.state.loading) {
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
      <View style={{ flex: 1 }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem

              title={item.name}
            />
          )}
          keyExtractor={item => item.name}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
        />
      </View>
    );
  }
}

export default Search;
import React,{Component}来自'React';
从“react native”导入{View、Text、FlatList、ActivityIndicator};
从“react native elements”导入{ListItem,SearchBar};
类搜索扩展组件{
建造师(道具){
超级(道具);
此.state={
加载:false,
数据:[],
错误:null,
};
this.arrayholder=[];
}
componentDidMount(){
这是makeRemoteRequest();
}
makeRemoteRequest=()=>{
常量url=`https://www.achhamall.com/staging-achhamall.com/index.php?route=webservices/api&method=appGetCategoryDetails`;
this.setState({loading:true});
获取(url)
.then(res=>res.json())
。然后(res=>{
这是我的国家({
数据:res.products,
错误:res.error | | null,
加载:false,
});
this.arrayholder=res.products;
console.log(res.products)
})
.catch(错误=>{
this.setState({error,loading:false});
});
};
RenderParator=()=>{
返回(
);
};
searchFilterFunction=文本=>{
这是我的国家({
值:文本,
});
const newData=this.arrayholder.filter(项=>{
const itemData=`${item.name.toUpperCase()}${item.name.toUpperCase()}`;
const textData=text.toUpperCase();
返回itemData.indexOf(textData)>-1;
});
这是我的国家({
数据:新数据,
});
};
renderHeader=()=>{
返回(
this.searchFilterFunction(text)}
自动更正={false}
value={this.state.value}
/>
);
};
render(){
if(this.state.loading){
返回(
);
}
返回(
(
)}
keyExtractor={item=>item.name}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
);
}
}
导出默认搜索;

当运行并键入要输入的文本时,如果error undefined不是对象(计算'this.arrayholder.filter')

请查看此代码段,了解如何使用搜索并在平面列表中实现它

     import React from 'react';
    import MapView,{ Marker } from 'react-native-maps';
    import {
      SafeAreaView,
      StyleSheet,
      ScrollView,
      View,
      Image,
  Text,
  ToastAndroid,
  PermissionsAndroid,
  StatusBar,
  Platform,

} from 'react-native';
import {Header,SearchBar,ListItem} from 'react-native-elements';
import Icon from 'react-native-vector-icons/MaterialIcons';

import {Fab} from 'native-base';
import { from } from 'rxjs';
const axios = require('axios');


class App extends React.Component{

  state = {
    search: '',
    searchResponse: [],
    isFlatlistVisible: false,

    loading: false
  };





  queryText = (text="") => {

    if(text==""){
      this.setState({searchResponse: []});


    }

    else{
      axios.get(`http:ww.gdhdhdh.com`)
      .then((response) => {

        this.setState({searchResponse: response.data.prop_data});

      });
    }
    }

  updateSearch = search => {

    this.setState({ search });
    this.queryText(search)
  };

  componentDidMount(){
   this.queryText()


  }
  render(){

    const{search} = this.state;
    const {searchResponse} = this.state;

    return(

      <>
      <StatusBar backgroundColor="blue" barStyle="light-content" />


     <SearchBar
       placeholder="Type Here..."
       onChangeText={this.updateSearch}
       value={search}

       />}

     />
    <View>

    </View>
     {this.state.search?<ScrollView>
     {
    searchResponse.map((item, i) => (

      <ListItem
        key={i}
        title={item.name}
        bottomDivider
        onPress= {() => ToastAndroid.show(`${item.name}`, ToastAndroid.SHORT)}
      />

    ))
  }
  </ScrollView>:<View style={styles.container}>

    </View> }


         </>
    );
  }
}

const styles = StyleSheet.create({
    container: {
     flex:1,
      alignItems: 'center',
    },
    map: {
      height: "100%",
      width: "100%",
    },
  textColor: {
    color: 'white',
    fontWeight: 'bold',
    fontSize: 20,
    marginBottom: 15
  },
  red: {
    color: 'red',
  },
});


    export default App;
从“React”导入React;
从“react native maps”导入MapView,{Marker};
进口{
安全区域视图,
样式表,
滚动视图,
看法
形象,,
文本,
蟾蜍,
许可证Sandroid,
状态栏,
平台,
}从“反应本机”;
从“react native elements”导入{Header、SearchBar、ListItem};
从“反应本机矢量图标/唯物主义者”导入图标;
从'native base'导入{Fab};
从'rxjs'导入{from};
const axios=require('axios');
类应用程序扩展了React.Component{
状态={
搜索:“”,
searchResponse:[],
isFlatlistVisible:false,
加载:错误
};
queryText=(text=”“)=>{
如果(文本==“”){
this.setState({searchResponse:[]});
}
否则{
get(`http:ww.gdhdh.com`)
。然后((响应)=>{
this.setState({searchResponse:response.data.prop_data});
});
}
}
updateSearch=搜索=>{
this.setState({search});
this.queryText(搜索)
};
componentDidMount(){
this.queryText()
}
render(){
const{search}=this.state;
const{searchResponse}=this.state;
返回(
}
/>
{this.state.search?
{
searchResponse.map((项目,i)=>(
ToastAndroid.show(`${item.name}`,ToastAndroid.SHORT)}
/>
))
}
:
}
);
}
}
const styles=StyleSheet.create({
容器:{
弹性:1,
对齐项目:“居中”,
},
地图:{
高度:“100%”,
宽度:“100%”,
},
文本颜色:{
颜色:'白色',
fontWeight:'粗体',
尺寸:20,
marginBottom:15
},
红色:{
颜色:“红色”,
},
});
导出默认应用程序;

发生这种情况的原因是您的数据没有获取arrayholder未定义请检查您的url。你可以用这个解决这个问题

this.arrayholder = res.products == undefined ? [] :res.products;
makeRemoteRequest函数中

检查下面的代码

import React, { Component } from 'react';
import { View, Text, FlatList, ActivityIndicator } from 'react-native';
import { ListItem, SearchBar } from 'react-native-elements';

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

    this.state = {
      loading: false,
      data: [],
      error: null,
    };

    this.arrayholder = [];
  }

  componentDidMount() {
    this.makeRemoteRequest();
  }

  makeRemoteRequest = () => {
    const url = `https://www.achhamall.com/staging-achhamall.com/index.php?route=webservices/api&method=appGetCategoryDetails`;
    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: res.products,
          error: res.error || null,
          loading: false,
        });
        this.arrayholder = res.products == undefined ? [] :res.products;
        console.log(res.products)
      })
      .catch(error => {
        this.setState({ error, loading: false });
      });
  };

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: '86%',
          backgroundColor: '#CED0CE',
          marginLeft: '14%',
        }}
      />
    );
  };

  searchFilterFunction = text => {
    this.setState({
      value: text,
    });
        console.log('dddd',this.arrayholder)
    const newData = this.arrayholder.filter(item => {
      const itemData = `${item.name.toUpperCase()} ${item.name.toUpperCase()}`;
      const textData = text.toUpperCase();

      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      data: newData,
    });
  };

  renderHeader = () => {
    return (
      <SearchBar
        placeholder="Type Here..."
        lightTheme
        round
        onChangeText={text => this.searchFilterFunction(text)}
        autoCorrect={false}
        value={this.state.value}
      />
    );
  };

  render() {
    if (this.state.loading) {
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
      <View style={{ flex: 1 }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem

              title={item.name}
            />
          )}
          keyExtractor={item => item.name}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
        />
      </View>
    );
  }
}

export default Search;
import React,{Component}来自'React';
从“react native”导入{View、Text、FlatList、ActivityIndicator};
从“react native elements”导入{ListItem,SearchBar};
类搜索扩展组件{
建造师(道具){
超级(道具);
此.state={
加载:false,
数据:[],
错误:null,
};
this.arrayholder=[];
}
componentDidMount(){
这是makeRemoteRequest();
}
makeRemoteRequest=()=>{
常量url=`https://www.achhamall.com/staging-achhamall.com/index.php?route=webservices/api&method=appGetCategoryDetails`;
this.setState({loading:true});
获取(url)
.then(res=>res.json())
。然后(res=>{
这是我的国家({
数据:res.products,
错误:res.error | | null,
加载:false,
});
this.arrayholder=res.products==未定义?[]:res.products;
console.log(res.products)
})
.catch(错误=>{
this.setState({error,loading:false});
});
};
RenderParator=()=>{
返回(
);
};
searchFilterFunction=文本=>{
这是我的国家({
值:文本,
});
console.log('dddd',this.arrayholder)
const newData=this.arrayholder.filter(项=>{
const itemData=`${item.name.toUpperCase()}${item.name.toUpperCase()}`;
const textData=text.toUpperCase();
返回itemData.indexOf(textData)>-1;
});
这是我的国家({
数据:新数据,
});
};
renderHeader=()=>{
返回(
this.searchFilterFunction(text)}
自动更正={false}
值={thi