android - ListView 中的搜索数据 react 原生
<p><p>我目前正在学习 react-native 并陷入 ListView 问题。我想从 TextInput 在 ListView 中搜索数据,我希望结果也在 ListView 中。</p>
<p>这是我到目前为止所做的:</p>
<p></p><div class="snippet"data-lang="js"data-hide="false"data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>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>
);
},</code></pre>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>在您的 fetchData 方法中,您可能也应该将 responseData 保存到 state。然后,您将在每次搜索字段更改时与此数据进行交互。</p>
<pre><code>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();
},
</code></pre>
<p>现在在您的 <code>setSearchText()</code> 方法中,您应该包含一些过滤器功能,该功能将从您保存到 <code>fetchData()</code> 中的状态的电影中找到您想要的电影。</p>
<pre><code>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);
});
},
</code></pre>
<p>每次要更新 ListView 时,都必须更新它的数据源。只有这样 ListView 组件才能意识到它显示的数据发生了变化。</p>
<p>希望我能帮上忙。</p></p>
<p style="font-size: 20px;">关于android - ListView 中的搜索数据 react 原生,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/37938189/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/37938189/
</a>
</p>
页:
[1]