【问题标题】:how to search item in listed element react native如何在列出的元素中搜索项目反应原生
【发布时间】:2021-10-04 09:56:47
【问题描述】:

我遇到了一个问题,当我试图从列出的数据中搜索元素时它不起作用,我似乎应用了很多文档广告,但它仍然对我有用,任何人都可以帮助我。 如果您有任何问题,请随时提出。

home.js

这是我编写所有代码的Home.js 文件。在这里我使用了一些 React 原生纸质组件。

import React, { useEffect, useState } from 'react'
import { Text, View, FlatList, StyleSheet, ScrollView, TouchableOpacity } from 'react-native';
import { Avatar } from 'react-native-elements';
import { Searchbar, Provider, Portal, TextInput, Button } from 'react-native-paper';
import { AntDesign, Entypo } from '@expo/vector-icons';
import Modal from "react-native-modal";

export default function Home() {

  const [searchquery, setSearchquery] = React.useState();
  const [isModalVisible, setModalVisible] = useState(false);
  const [name, setName] = React.useState('');
  const [number, setNumber] = React.useState('');


  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };

    const filterItem = (text) => {
      users.filter((item) => {
        return item.name.toLowerCase().inludes(text.toLowerCase())
      })
      setSearchquery(text)
  }

  

  const [users, setUser] = useState([
    {
      id: 1,
      name: "Ashish Nirvikar",
      number: 3289768909,
    },
    {
      id: 2,
      name: "Drew Macntyre",
      number: 3345661276
    },
    {
      id: 3,
      name: "Jonh Cena",
      number: 9087392878
    },
    {
      id: 4,
      name: "Rock Samoa",
      number: 9723780928
    },
    {
      id: 5,
      name: "Boby Lashely",
      number: 8769213678
    },
    {
      id: 6,
      name: "Seth Rollins",
      number: 6890326741
    },
  ])

  return (
    <View >
      <Searchbar
        placeholder="Search Contacts"
        onChangeText={(text) => setSearchquery(text)}
        value={searchquery}
        style={{ marginTop: 30, marginHorizontal: 10 }}
      />
   <ScrollView>
     {
          filterItem(users).map((item, index) => {
            return (
              <View key={index} style={styles.names}>
                <Text style={{ color: 'black', fontSize: 20, fontWeight: 'bold' }}>Name : {item.name}</Text>
                <Text style={{ color: 'black' }}>Mobile no : {item.number}</Text>
              </View>
            )
          })
        }
     </ScrollView>

      <Modal isVisible={isModalVisible} style={{ backgroundColor: 'white', height: 50, marginBottom: 200, marginTop: 100 }}>
        <View style={{ flex: 2 }}>
          <Text style={{ color: 'black', fontSize: 50, textAlign: 'center' }}>Add Contact</Text>
          <TextInput
            style={styles.input}
            label="Enter Full name"
            value={name}
            onChangeText={text => setName(text)}
          />
          <TextInput
            style={styles.input1}
            label="Enter Mobile Number"
            value={number}
            onChangeText={text => setNumber(text)}
          />
          <Button title="Hide modal" onPress={toggleModal} style={{ color: 'black', backgroundColor: 'white', borderWidth: 1, borderColor: 'gray', marginHorizontal: 10, marginTop: 15 }}>Cancle</Button>
        </View>
      </Modal>

      <AntDesign name="plus" size={34} color="black" style={styles.plus} onPress={toggleModal} />
    </View>
  );
}


const styles = StyleSheet.create({
  customText: {
    padding: 10,
    marginTop: 20,
    textAlign: 'center',
    backgroundColor: 'lightgray',
    fontWeight: 'bold',
    fontSize: 20
  },
  plus: {
    fontSize: 50,
    position: 'absolute',
    top: 680,
    right: 40,
    backgroundColor: 'pink',
    borderRadius: 15,
    borderWidth: 0.5,
    padding: 5,
  },
  names: {
    padding: 15,
    fontSize: 25,
    fontWeight: 'bold',
    backgroundColor: 'lightgray',
    marginTop: 10,
    borderRadius: 20,
    color: 'black'
  },
  addcontactname: {
    fontSize: 30,
    textAlign: 'center',
    marginTop: 10,
    marginBottom: 30
  },
  input: {
    marginHorizontal: 10,
    marginBottom: 20,
    marginTop: 20
  },
  input1: {
    marginHorizontal: 10,
    marginBottom: 10,
  }
});

【问题讨论】:

    标签: react-native react-hooks expo


    【解决方案1】:

    您的Searchbar 应该是一个受控输入(使用Searchbar 中的更改值调用setSearchquery)。

    然后你可以使用searchquery的值在你的jsx中执行过滤。

    最后,使用FlatList 来呈现项目列表而不是ScrollView 内的地图。

    在您的示例中,不需要将用户列表存储在状态中。

    import React, { Component } from 'react';
    import { Text, View, StyleSheet, ScrollView, FlatList } from 'react-native';
    import { Searchbar } from 'react-native-paper';
    
    const data = [...];
    
    export default class Home extends Component {
      constructor(props) {
        super(props);
        this.state = {
          searchquery: '',
        };
      }
    
      renderHeader = () => {
        return (
          <Searchbar
            placeholder="Search Contacts"
            onChangeText={(searchquery) =>
              this.setState({
                searchquery,
              })
            }
            value={this.state.searchquery}
          />
        );
      };
    
      renderItem = ({ item, index }) => {
        return (
          <View key={index} style={styles.names}>
            <Text>
              Name : {item.name}
            </Text>
            <Text>Mobile no : {item.number}</Text>
          </View>
        );
      };
    
      render() {
        return (
          <FlatList
            data={data.filter((item) => {
              if (!this.state.searchquery) return true
              return item.name
                .toUpperCase()
                .includes(this.state.searchquery.toUpperCase());
            })}
            ListHeaderComponent={this.renderHeader}
            renderItem={this.renderItem}
          />
        );
      }
    }
    

    Snack

    【讨论】:

      【解决方案2】:

      如果此代码不起作用,您可以尝试使用此代码,然后使用括号和参数调用 filterItem 函数,我的代码在名称为小写时也可以正常工作。

      <Searchbar
          placeholder="Search Contacts"
          onChangeText={filterItem}
          onClear={(users) => setUser('')}
          value={searchquery}
          style={{ marginTop: 30, marginHorizontal: 10 }}
      />
      
      const filterItem = (text) => {
          setSearchquery(text)
          let searchText = text.toLowerCase()
          let filterData = users
          filterData = filterData.filter(function (id) {
            return id.name.toLowerCase().includes(searchText)
          })
          setUser(filterData);
          if (text === "") {
           setUser(
      [
          {
            id: 1,
            name: "Ashish Nirvikar",
            number: 3289768909,
          },
          {
            id: 2,
            name: "Drew Macntyre",
            number: 3345661276
          },
          {
            id: 3,
            name: "Jonh Cena",
            number: 9087392878
          },
          {
            id: 4,
            name: "Rock Samoa",
            number: 9723780928
          },
          {
            id: 5,
            name: "Boby Lashely",
            number: 8769213678
          },
          {
            id: 6,
            name: "Seth Rollins",
            number: 6890326741
          },
        ]
      );
          }
      }
      

      【讨论】:

      • @novonimo 我也浏览了你的代码,在你的代码搜索文本中工作正常,但是当我试图切断它时,它不起作用
      • @MonuPatil 显然 bcz 我们设置条件如果文本为空它不会重置 filterItem 中的第一个用户检查条件它将设置最后状态用户数据
      • 请告诉我应该在哪里更新我的代码
      • 更新后的代码,你可以设置用户值,如果文本为空白,你可以设置与最初提供的值相同,我猜这会起作用
      • @vivan 我已经更新了,但仍然出现用户未定义的错误
      【解决方案3】:

      试试这个

      
      
       const filterItem = (searchItems) => {
            searchItems.filter((item) => {
              return item.name.toLowerCase().inludes(searchquery.toLowerCase())
            })
          
        }
      
      
      <Searchbar
              placeholder="Search Contacts"
              onChangeText={(text) => setSearchquery(text)}
              onClear={(text) => searchquery("")}
              value={searchquery}
              style={{ marginTop: 30, marginHorizontal: 10 }}
            />
         <ScrollView>
           {
                filterItem(users).map((item, index) => {
                  return (
                    <View key={index} style={styles.names}>
                      <Text style={{ color: 'black', fontSize: 20, fontWeight: 'bold' }}>Name : {item.name}</Text>
                      <Text style={{ color: 'black' }}>Mobile no : {item.number}</Text>
                    </View>
                  )
                })
              }
           </ScrollView>
      
      

      【讨论】:

      • 收到错误 text.toLowercase() 不是函数
      • @MonuPatil 这里更新了代码
      • @shafayat 我更新了我的你现在可以结帐
      • @MonuPatil 现在检查我的代码并应用它
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      相关资源
      最近更新 更多