React Native——电影列表

简单的介绍ListView组件的使用
ListView 会安排视图的渲染,只显示当前在屏幕上的那些元素,而那些已经渲染好了但移动到了屏幕之外的元素,则会从原生视图结构中移除,从而提高性能。

首先要做的事情,从React中引入ListView

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Image,
  ListView,
  TouchableHighlight,
  View
} from 'react-native';

在constructor 中初始化dataSource

constructor(props){
    super(props);
    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged:(row1,row2)=>row1 !==row2,
      }),
      loaded:false,
    };
  }

loaded状态来判断数据是否加载成功.

现在来看看render函数

render() {
        if(!this.state.loaded){
          return this.renderLoadingView();
        }

        return(
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this.renderMovie}
            style={styles.listView}
            />
        );
  }

如何loaded为false 加载renderLoadingView

renderLoadingView(){
    return(
      <View style={styles.container}>
        <Text>
          正在加载电影...
        </Text>
      </View>
    );
  }

在组件加载完成后刷新数据

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();
  }

通过setSate刷新界面

renderMovie(movie){
    return(

      <View style={styles.container}>

        <Image source={{uri:movie.posters.thumbnail}} style={styles.thumbnail}/>

        <View style={styles.right}>
            <Text>
              {movie.title}
            </Text>
            <Text>
              {movie.year}
            </Text>
          </View>

      </View>
       );

这样就可以将电影列表显示出来了。
接下来添加item的点击事件
修改之后的代码:
采用bind

return(
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this.renderMovie.bind(this)}
            style={styles.listView}
            />
        );
renderMovie(movie){
    return(
      <TouchableHighlight onPress={this.alertImage.bind(this,movie)}>

      <View style={styles.container}>

        <Image source={{uri:movie.posters.thumbnail}} style={styles.thumbnail}/>

        <View style={styles.right}>
            <Text>
              {movie.title}
            </Text>
            <Text>
              {movie.year}
            </Text>
          </View>

      </View>

      </TouchableHighlight>
    );
  }
alertImage(movie){
     alert(movie.title);
   }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值