刷新以获取FlatList中的新项目

时间:2017-11-01 09:10:59

标签: react-native react-native-flatlist

我有app.js来渲染来自Card.js的许多卡片,但一次只显示3张卡片。在app.js我有刷新按钮,当我按下时会隐藏当前的显示牌(3张牌)并显示3张新牌。

App.js

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  StatusBar,
  Linking,
  FlatList
} from 'react-native';

import Card from './Card'

const data = [
  {key: 'Devin'},
  {key: 'Jackson'},
  {key: 'James'},
  {key: 'Joel'},
  {key: 'John'},
  {key: 'Jillian'},
  {key: 'Jimmy'},
  {key: 'Julie'}
]

export default class App extends Component {
    constructor(props) {
     super(props);
     this.state = {
       itemsCount: 3,
       hide: false
     };
   }
   renderNewItem = () => {
     if (this.state.itemsCount < data.length) {
       this.setState((prevState) => ({ itemsCount: (prevState.itemsCount + 1) }));
     }
   }

   renderCard = ({item}) => {
     return (
       <Card
        text={item.key}
        onPress={this.renderNewItem}
        hide={this.state.hide}
       />
     )
   }

   refreshItem = () => {
     this.setState({hide: true})
     if (this.state.itemsCount < data.length) {
       this.setState((prevState) => ({ itemsCount: (prevState.itemsCount + 3) }));
     }
   }

   render() {
     return (
       <View style={styles.container}>
        <Text
          style={{margin: 30, alignSelf: 'center'}}
          onPress={this.refreshItem}
        >
          REFRESH ITEMS
        </Text>
         <FlatList
           data={data.slice(0, this.state.itemsCount)}
           keyExtractor={(item, index) => item.key}
           renderItem={this.renderCard}
         />
       </View>
     )
   }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center'
  },
  text: {
    textAlign: 'center',
    lineHeight: 30
  }
});

Card.js

import React from 'react'
import {
  Text,
  View
} from 'react-native'

export default class Card extends React.Component {
  render () {
    if (this.props.hide) {
      return null
    }
    return (
      <View style={styles.viewStyle}>
        <Text onPress={this.props.onPress}>{this.props.text}</Text>
      </View>
    )
  }
}

const styles = {
  viewStyle: {
    height: 100,
    width: 300,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: 'black'
  }
}

问题是当我按下刷新按钮时,所有卡都会消失。 我想要的只是目前只显示卡片消失,接下来会出现3张卡片。

0 个答案:

没有答案