React Native-使用react钩子在对象上搜索数组

时间:2020-04-28 04:17:01

标签: react-native react-hooks

我在名为data的变量中有一个对象数组。 数组如下所示:

const data = [
      {
        "id": "0.804802585702977",
        "value": "Bar",
      },
      {
        "id": "0.9359341974615858",
        "value": "Mar",
      },
      {
        "id": "0.4182922963461958",
        "value": "Naba",
      },
      {
        "id": "0.6132336648416628",
        "value": "Socerr",
      },
      {
        "id": "0.060587558948085984",
        "value": "Mall",
      },
    ]

我想创建一个搜索栏来搜索该数组内的所有值,如果搜索文本等于该数组内的值,用户将能够看到该值? 请帮忙吗?

1 个答案:

答案 0 :(得分:1)

您需要使用filter函数从数组中搜索/排序数据。请检查以下内容是否可以解决您的问题。

import React, { useState } from "react";
import { Text, TextInput, View, StyleSheet } from "react-native";
import Constants from "expo-constants";

// You can import from local files
import AssetExample from "./components/AssetExample";

// or any pure javascript modules available in npm
import { Card } from "react-native-paper";

const data = [
  {
    id: "0.804802585702977",
    value: "Bar",
  },
  {
    id: "0.9359341974615858",
    value: "Mar",
  },
  {
    id: "0.4182922963461958",
    value: "Naba",
  },
  {
    id: "0.6132336648416628",
    value: "Socerr",
  },
  {
    id: "0.060587558948085984",
    value: "Mall",
  },
];
export default function App() {
  let [filteredData, setFilteredData] = useState(data);

  function _searchFilterFunction(searchText, data) {
    let newData = [];
    if (searchText) {
      newData = data.filter(function(item) {
        const itemData = item.value.toUpperCase();
        const textData = searchText.toUpperCase();
        return itemData.includes(textData);
      });
      setFilteredData([...newData]);
    } else {
      setFilteredData([...data]);
    }
  }

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>Search Here.</Text>
      <TextInput
        style={styles.input}
        underlineColorAndroid="transparent"
        placeholder="Search"
        placeholderTextColor="#9a73ef"
        autoCapitalize="none"
        onChangeText={(value) => {
          _searchFilterFunction(value, data);
        }}
      />
      {filteredData.map((item, index) => {
        return <Text style={styles.paragraph}>{item.value}</Text>;
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,

    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8,
  },
  input: {
    margin: 15,
    height: 40,
    paddingLeft: 10,
    borderRadius: 2,
    borderColor: "#7a42f4",
    borderWidth: 1,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center",
  },
});