React-Native Javascript搜索过滤器功能

时间:2020-09-15 08:06:33

标签: javascript arrays react-native search

我正在尝试在此数组中搜索这些成分,并将其值添加到~/Library/Containers/…/Data/Library/Application Support/… 中以显示它,但是它不起作用。我对javascript很陌生,因此如果有人足够帮助我,我将不胜感激。这是我所做的:

data

1 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

import React, { useState } from 'react';
import { Text, TextInput, View } from 'react-native';

export default function App() {
  const ingridients = [
    'paprika',
    'parsley',
    'steak',
    'ground beef',
    'milk',
    'eggs',
    'cheese',
  ];
  const [input, setInput] = useState();
  const [filteredData, setFilteredData] = useState([]);

  const filter = (term) => {
    setInput(term);
    if(/\d/.test(term) || /[a-zA-Z]/.test(term)) {
        setFilteredData(ingridients.filter(ingridient => ingridient.includes(term)));
    } 
    else {
       setFilteredData([]);
    }
  };
  return (
    <React.Fragment>
      <TextInput
        onChangeText={(text) => filter(text)}
        value={input}
        style={{ backgroundColor: 'grey' }}
      />
      <View style={{ padding: 40 }}>
        {filteredData.map(ingridient => (
          <Text style={{ color: 'black' }}>{ingridient}</Text>
        ))}
      </View>
    </React.Fragment>
  );
}