React Native 结合ScrollableTab、RefreshControl和FlatList实现新闻分类列表

版权声明:本文为博主原创文章,转载请附原博客地址。侵权必究 https://blog.csdn.net/wapchief/article/details/79991315

正好刚开始学RN,熟悉一下控件和基本使用。

涉及的知识点:

1、fetch网络请求,get 拼接参数,解析json。
2、ScrollableTabView、ScrollableTabBar 分类布局。
3、FlatList 数据列表。
4、Navigation 路由携带参数跳转。
5、下拉刷新,结合了 Tab 切换数据更新

需要导入到 RN 的第三方库:

react-native-scrollable-tab-view
导入方法:
1、在项目的根路径使用下面命令行

npm install react-native-scrollable-tab-view --save

2、检查项目的 package.json 中的 dependencies 下是否添加进来了,如果没有就手动依赖下,版本号要一致。
https://badge.fury.io/js/react-native-scrollable-tab-view

  "dependencies": {
    "react": "^16.3.0-alpha.1",
    "react-native": "0.54.4",
    "react-native-deprecated-custom-components": "latest",
    "react-native-image-picker": "^0.26.7",
    "react-native-scrollable-tab-view": "^0.8.0",
    "react-native-swiper": "^1.5.13",
    "react-navigation": "^1.5.11"
  }

建议安装 rnmp 自动依赖工具,这样就不需要在导包的时候再手动去添加本地依赖。

npm install rnpm -g
rnpm link

页面布局

1、可滚动的 TabView

使用前需要先导入到当前 js

import ScrollableTabView, { DefaultTabBar, ScrollableTabBar } from 'react-native-scrollable-tab-view'

DefaultTabBar 和 ScrollableTabBar 是可选择是否超出屏幕滚动。前者适用于固定的 Tabbar。后者适用于有多种分类的滚动 Tab。
onChangeTab 是 Tab 点击切换的监听,在这里可以执行刷新等效果。


    return (
      <ScrollableTabView
        initialPage={0}
        renderTabBar={() => <ScrollableTabBar/>}
        tabBarUnderlineStyle={{}}
        onChangeTab={(obj) => {
          this._onRefresh(news[obj.i])
        }}
      >
        <Text tabLabel='头条'/>
        <Text tabLabel='社会'/>
        <Text tabLabel='国内'/>
        <Text tabLabel='国际'/>
        <Text tabLabel='娱乐'/>
        <Text tabLabel='体育'/>
        <Text tabLabel='军事'/>
        <Text tabLabel='科技'/>
        <Text tabLabel='财经'/>
        <Text tabLabel='时尚'/>
      </ScrollableTabView>
    )
2、下拉刷新Refresh+FlatList

FlatList 和 ListView 一样,不过 FlatList 处理列表的效率更高,所以建议使用,而且内置的方法有支持 iOS 和 Android 平台的下拉刷新效果。

而且给 List 添加分割线和 Header 也很简单。

RefreshControl 就是下拉刷新的布局,Android 和 iOS 在刷新样式上有所不同。


return (
        <FlatList
          data={this.state.result.data}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
          ListHeaderComponent={this._headerTabView()}
          ItemSeparatorComponent={this._itemDivide}
          refreshControl={
            <RefreshControl
              refreshing={this.state.refreshing}
              onRefresh={this._onRefresh.bind(this,this.state.newsType)}
            />
          }
        />

    )
3、列表的Item布局

需要在外层使用 TouchableOpacity 获取整个 View 的点击事件。
通过 item 展示和解析数据。在 RN 中不需要定义每个 json 数据的字段名称 。所以在解析的时候直接使用参数名调用就能拿到数据。

  _renderItem = ({item, index}) => {
    return (
      <TouchableOpacity
        activeOpacity={0.5}
        onPress={this.itemClick.bind(this, item, index)}>
        <View style={{backgroundColor: '#ffffff', padding: 10, flexDirection: 'row'}}>

          <Image source={{uri: item.thumbnail_pic_s02}} style={styles.imgStyle}/>

          <View style={{flex: 1, flexDirection: 'column'}}>

            <Text style={{
              paddingRight: 10,
              marginLeft: 10,
              width: screenWidth * 0.65,
              height: 80 * 0.7
            }}>{item.title}</Text>

            <View style={{flexDirection: 'row', paddingLeft: 10, paddingRight: 10}}>
              <Text style={styles.subTitle}>{item.category + '  ' + item.author_name}</Text>
              <Text style={styles.subTitle}> {item.date}</Text>
            </View>
          </View>

        </View>

      </TouchableOpacity>
    )
  }

具体实现

1、声明一些变量

为了方便查看获取到的 json 这里直接按照 API 返回的格式去定义变量。

 constructor (props) {
    super(props)
    //在这里定义json返回的key
    this.state = {
      //控制分类展示
      isShow: false,
      //分类
      newsType: 'top',
      //下拉刷新
      refreshing: false,
      //data数据
      resultJson: null,
      error_code: '',
      reason: '',
      result: {
        data: ''
      }
    }
  }
2、通过网络获取数据源

这里我使用了一个阿里的新闻 API 。
需要在请求的时候将申请到的 appCode 以添加请求头的方式提供给 API 。

如果不需要指定获取新闻的类型,则不需要提供 type 类型。

// type类型:top(头条,默认),shehui(社会),guonei(国内),guoji(国际),yule(娱乐),tiyu(体育)junshi(军事),keji(科技),caijing(财经),shishang(时尚)

fetch 就是执行网络请求的入口。

第一个 .then 是为了指定获取到的 json 以什么样的格式返回,如果需要解析可以直接返回 json 格式,方便下面的解析操作。
同时在成功拿到数据之后,需要将刷新状态设置为 false ,关闭下拉刷新的状态。

第二个 .then 就是通过第一个返回的类型数据,已经格式化好了。只需要解析并赋值就行。

同样当遇到请求错误的情况,通过 catch 抛出异常,在方法内处理异常。

const header = new Headers()
 getRequest (url, type) {
    /*网络请求的配置*/
    header.append('Authorization', appCode)
    const opts = {
      method: 'GET',
      headers: header,
    }
    fetch(url + '?type=' + type, opts)
      .then((response) => {
        this.setState({refreshing: false})
        return response.json()
      })
      .then((responseJson) => {
        this.setState({
          resultJson: responseJson,
          error_code: responseJson.error_code,
          reason: responseJson.reason,
          result: responseJson.result,
          data: responseJson.result.data,
        })
        // alert(this.state.reason)
      })
      .catch((error) => {
        alert(error)
      })
  }
3、下拉刷新

在 RefreshControl 布局的 onRefresh 方法中调用。调用的时候,重新开启下拉刷新的效果。


  //下拉刷新
  _onRefresh (type) {
    this.setState({refreshing: true})
    this.getRequest(newsUrl, type)
  }
4、其它

1.
componentDidMount 是在 render 方法进来之后立即调用的方法。
类似于 Android上的onViewCreate 方法,一般在这个方法内可以先进行网络请求,消息订阅等操作。

  componentDidMount () {
    this.getRequest(newsUrl, this.state.newsType)
  }

2.
跳转需要用到路由,关于路由的使用有时间再整理。

  //列表点击跳转事件
  itemClick (item, index) {
    // alert('新闻标题:' + item.author_name + '\n时间:' + item.date+'\n'+item.thumbnail_pic_s);
    this.props.navigation.navigate('Details', {
      title: item.title,
      url: item.url,
    })
  }

3.

 //List列表分割线
  _itemDivide = () => {
    return (
      <View style={{height: 10}}/>
    )
  }

关于

  • 语法使用ES6标准
  • React Native 版本 0.54.4

Demo:https://github.com/wapchief/ReactNativeDemo
有兴趣一起学习的朋友可以关注下,将持续更新学习进度,在 Demo 上体现。
目前其它实现的功能有:banner轮播、相册和相机调用、网页加载。

猜你喜欢

转载自blog.csdn.net/wapchief/article/details/79991315