React Native——电影列表

来源:互联网 发布:java和web前端的区别 编辑:程序博客网 时间:2024/05/07 21:35

简单的介绍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);   }
0 0
原创粉丝点击