gpt4 book ai didi

android - 如何在 react-native 中使用列表项制作搜索过滤器

转载 作者:行者123 更新时间:2023-12-01 23:16:22 28 4
gpt4 key购买 nike

我一直想在此列表项中进行搜索过滤,但我有点困惑,如果您对此有经验,请查看我的代码。

import React, { Component } from 'react'; 
import { Text, View, ScrollView, TextInput, } from 'react-native';
import { List, ListItem } from 'react-native-elements';
import { users } from '../config/data';

class Feed extends Component { constructor(props){
super(props);
this.state = {
user:'',
} } onLearnMore = (user) => {
this.props.navigation.navigate('Details', { ...user }); };

filterSearch(text){
const newData = users.filter((item)=>{
const itemData = item.name.first.toUpperCase()
const textData = text.toUpperCase()
return itemData.indexOf(textData)>-1
})
this.setState({
text:text
}) }

render() {
return (
<ScrollView>
<TextInput
onChangeText={(text) => this.filterSearch(text)}
value={this.state.text}
/>
<List>
{users.map((user) => (
<ListItem
key={user.login.username}
roundAvatar
avatar={{ uri: user.picture.thumbnail }}
title={`${user.name.first.toUpperCase()} ${user.name.last.toUpperCase()}`}
subtitle={user.email}
onPress={() => this.onLearnMore(user)}
/>
))}
</List>
</ScrollView>
); } }

export default Feed;

我一直在网上冲浪,但我发现其中大部分都在讨论 listview 而不是 react-native-elements 中的列表项,帮帮我!

最佳答案

你几乎是正确的。您成功过滤了您的用户,但随后在您的列表中呈现了相同的未过滤用户。要轻松更改此设置,您可以使用组件状态。

示例

import React, { Component } from 'react'; 
import { Text, View, ScrollView, TextInput, } from 'react-native';
import { List, ListItem } from 'react-native-elements';
import { users } from '../config/data';

class Feed extends Component {
constructor(props){
super(props);
this.state = {
user:'',
users: users // we are setting the initial state with the data you import
}
}

onLearnMore = (user) => {
this.props.navigation.navigate('Details', { ...user });
};

filterSearch(text){
const newData = users.filter((item)=>{
const itemData = item.name.first.toUpperCase()
const textData = text.toUpperCase()
return itemData.indexOf(textData)>-1
});
this.setState({
text:text,
users: newData // after filter we are setting users to new array
});
}

render() {
// rather than mapping users loaded from data file we are using state value
return (
<ScrollView>
<TextInput
onChangeText={(text) => this.filterSearch(text)}
value={this.state.text}
/>
<List>
{this.state.users.map((user) => (
<ListItem
key={user.login.username}
roundAvatar
avatar={{ uri: user.picture.thumbnail }}
title={`${user.name.first.toUpperCase()} ${user.name.last.toUpperCase()}`}
subtitle={user.email}
onPress={() => this.onLearnMore(user)}
/>
))}
</List>
</ScrollView>
); } }

export default Feed;

关于android - 如何在 react-native 中使用列表项制作搜索过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46805836/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com