我终于想通了。此代码根据特定项目名称进行搜索。
数据库
{
"directory" : {
"macintosh" : {
"address" : "117 East 11th Street, Hays, KS 67601",
"firstLetter" : "m",
"title" : "Macintosh",
},
"apple" : {
"address" : "117 East 11th Street, Hays, KS 67601",
"firstLetter" : "a",
"title" : "apple",
},
},
带搜索栏的列表视图
render() {
return (
<View style={styles.container}>
<ScrollView>
<SearchBar
returnKeyType='search'
lightTheme
placeholder='Search...'
onChangeText={(text) => this.setState({searchText:text})}
onSubmitEditing={() => this.firstSearch()}
/>
{
this.state.loading &&
<ActivityIndicator
size="large"
color="#3498db"
style={styles.activityStyle}
/>
}
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderItem.bind(this)}
enableEmptySections={true}
/>
</ScrollView>
</View>
);
}
搜索功能
firstSearch() {
this.searchDirectory(this.itemsRef);
}
searchDirectory(itemsRef) {
var searchText = this.state.searchText.toString();
if (searchText == ""){
this.listenForItems(itemsRef);
}else{
itemsRef.orderByChild("searchable").startAt(searchText).endAt(searchText).on('value', (snap) => {
items = [];
snap.forEach((child) => {
items.push({
address: child.val().address,
firstLetter: child.val().firstLetter,
title: child.val().title,
});
});
this.setState({
dataSource: this.state.dataSource.cloneWithRows(items)
});
});
}
}
这通过使用 orderbychild.startat().endat() firebase 函数替换 listview 数据源来搜索 firebase。这是最接近“SELECT * BY %LIKE%” sql 搜索功能的东西。
我修改了我的代码以按第一个字母进行搜索。所以万一有人搜索“Macbuk”,它仍然会显示“Macbook”结果。它只搜索 M。我在我的数据库中添加了另一个字段到标题的第一个字母进行搜索并将其设为小写。