我目前正在学习 react-native 并陷入了 ListView 问题。我想从 TextInput 搜索 ListView 中的数据,我希望结果也在 ListView 中。
这是我到目前为止所做的:
var PageOne = React.createClass({
getInitialState:function(){
return{
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
colorProps: {
titleColor: 'white',
},
searchText:"",
}
},
componentDidMount() {
this.fetchData();
},
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true,
});
})
.done();
},
setSearchText(action){
let searchText = event.nativeEvent.text;
this.setState({searchText});
/*
*
*
*/
},
render() {
return (
<View style={{ flex: 1 }}>
<ToolbarAndroid
title="Movies"
{...this.state.colorProps}
style={{height:40, backgroundColor:'blue'}}
/>
<TextInput
placeholder="Search movies......."
value={this.state.searchText}
onChange={this.setSearchText.bind(this)} />
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
</View>
);
},
renderMovie(movie) {
return (
<TouchableOpacity onPress={this._handlePressList.bind(this, movie)}>
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
</TouchableOpacity>
);
},
接下来我该做什么?请帮忙。谢谢:)
更新!阅读 urbancvek 的答案后,我在 setSearchText()
方法中添加函数,如下所示:
setSearchText(event){
const searchText = event.nativeEvent.text;
moviesLength = this.state.movies.length;
aMovie = this.state.movies;
const filteredMovies = this.state.movies.filter(checkTitle);
console.log("movies: " + JSON.stringify(filteredMovies));
function checkTitle() {
for(i=0;i<moviesLength;i++){
if(aMovie[i].title === searchText){
console.log("found: " + aMovie[i].title);
return aMovie[i];
}
}
}
this.setState({
searchText,
dataSource: this.state.dataSource.cloneWithRows(filteredMovies),
});
},
但它总是向我显示所有电影,而不是经过过滤的电影。有任何想法吗?谢谢
最佳答案
在您的 fetchData 方法中,您可能也应该将 responseData 保存到 state。每次搜索字段发生变化时,您都会与这些数据进行交互。
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
movies: responseData.movies,
loaded: true,
});
}).done();
},
现在,在您的 setSearchText()
方法中,您应该包含一些筛选函数,该函数将从您保存到 fetchData()
状态的电影中找到您想要的电影。
setSearchText(action){
const searchText = event.nativeEvent.text;
const filteredMovies = this.state.movies.filter(/* awesome filter function */);
this.setState({
searchText,
dataSource: this.state.dataSource.cloneWithRows(filteredMovies);
});
},
每次你想更新 ListView 时,你都必须更新它的数据源。只有这样 ListView 组件才能意识到它显示的数据发生了变化。
希望我有所帮助。
关于android - ListView 中的搜索数据 react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37938189/