如何为scrollView添加ActivityIndi cator?

问题描述 投票:1回答:1

我试图在ScrollView中添加ActivityIndi​​cator以显示20个项目。加载后,它将显示更多20项。

在下面的代码中,ActivityIndi​​cator显示在scrollView的末尾,但是在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;
javascript reactjs react-native
1个回答
0
投票

我可以看到,一旦用户滚动到最后,你需要显示加载。对于这个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;
© www.soinside.com 2019 - 2024. All rights reserved.