我正在尝试在flatlist中添加搜索栏,这里正在获取来自API的数据并在Flatlist上填充数据,但是我必须过滤该列表,因为它可能包含许多数据。所以请为此帮助我。我尝试了几个示例,但要遇到错误,所以有时没有发生任何事情。请查看和帮助
import React, { Component } from 'react';
import { View, Text, TextInput,
FooterTab,Button,TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator ,Header,FlatList} from 'react-native';
import {Icon} from 'native-base';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
export default class RenderList extends Component {
static navigationOptions = {
title: 'Selected Item',
header: null,
};
constructor() {
super();
this.state = {
data: null,
loading: true,
search: '',
};
}
componentDidMount() {
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'http://Dsenze/userapi/grouphier/viewgroup',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password: 'admin',
username: 'admin',
viewall: 'false',
id: [4],
startlimit: '0',
valuelimit: '10',
}),
}
);
const responseJson = await response.json();
const { groupData } = responseJson;
this.setState({
data: groupData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
clickedItemText(clickedItem) {
this.props.navigation.navigate('Item', { item: clickedItem });
}
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ name }) => name.toString();
renderItem = ({ item }) => (
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}>
<Text>Hospital Id {item.id}</Text>
<Text>Hospital Name {item.name}</Text>
</TouchableOpacity>
);
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
}}
/>
);
};
render_FlatList_header = () => {
var header_View = (
<View style={styles.header_footer_style}>
<Text style={styles.textStyle}> FlatList Header </Text>
</View>
);
return header_View ;
};
render() {
const { loading, data } = this.state;
return (
<ScrollView>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={data}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.render_FlatList_header}
/>
)}
</View>
</ScrollView>
);
}
}
谢谢...
因此,您需要保留数据的原始值,然后可以根据密钥输入过滤它,并设置以在flatlist中显示的状态。例如,在更改文本上,如果输入,则您过滤对象的匹配子字符串,然后将其放入新数组中,并将其设置在filterByValue
数组中,该数组将在flatlist中显示。
onSearchInputChange = (text) => {
const filterByValue = this.state.data.filter(x =>
x.name.toLowerCase().includes(text.toLowerCase()));
this.setState({
searchText: text,
filterByValue
});
}
然后将flatlist的数据作为
传递<FlatList
data={filterByValue}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.render_FlatList_header}
/>
对于工作示例,请尝试https://snack.expo.io/rjy0gyliv