我正在尝试在 ScrollView 中添加活动指示器以显示 20 个项目。 加载后,它将显示更多 20 个项目。
在下面的代码中,活动指示器显示在滚动视图的末尾,但我在 20 个项目后需要它。
import React, { Component } from 'react';
import { View, ScrollView, Alert, ActivityIndicator } from 'react-native';
import AlbumDetail from './AlbumDetail';
import axios from 'axios';
class AlbumList extends Component {
state = {
isLoading: false,
albums: [],
};
componentWillMount() {
axios
.get('http://www.json-generator.com/api/json/get/cqgdfqryzS?indent=2')
.then(response => this.setState({ albums: response.data }));
}
componentDidMount() {
{this.setState({ isLoading: false })}
}
renderAlbums() {
return this.state.albums.map(album => (
<AlbumDetail key={album.name} album={album} />
));
}
render() {
return (
<ScrollView>
{this.renderAlbums()}
<ActivityIndicator size="large" color="#0000ff" />
</ScrollView>
);
}
}
export default AlbumList;
正如我所看到的,一旦用户滚动到最后一个,您需要显示加载。为此,FlatList
似乎是除ScrollView
之外最好的组件。 当列表滚动到最后一个时ListFooterComponent
将自动调用 prop。所以重构你的代码如下:
import React, { Component } from 'react';
import { View, FlatList, Alert, ActivityIndicator } from 'react-native';
import AlbumDetail from './AlbumDetail';
import axios from 'axios';
class AlbumList extends Component {
state = {
isLoading: false,
albums: [],
};
componentWillMount() {
axios
.get('http://www.json-generator.com/api/json/get/cqgdfqryzS?indent=2')
.then(response => this.setState({ albums: response.data }));
}
componentDidMount() {
{this.setState({ isLoading: false })}
}
Render_Footer=()=>{
return (
<ActivityIndicator size="large" color="#0000ff" />
)
}
render() {
return (
<FlatList
keyExtractor = {( item, index ) => index }
data = { this.state.albums}
renderItem = {({ item }) => <AlbumDetail key={item.name} album={item } />}
ListFooterComponent = { this.Render_Footer }
/>
);
}
}
export default AlbumList;