美文网首页
学习React Native日记二,Movie Fetcher

学习React Native日记二,Movie Fetcher

作者: PreFU | 来源:发表于2016-07-25 22:47 被阅读0次

查询官方指导进行了工程创建。

导入组件

import React, { Component } from 'react';
import {
AppRegistry,
Image,
StyleSheet,
Text,
View,
ListView      //用于列表显示
} from 'react-native';

单条模拟数据

var MOCKED_MOVIES_DATA = [
{title: '标题', year: '2015', posters: {thumbnail: 'https://i.imgur.com/UePbdph.jpg'}},
  ];   //定义数据,JSON格式
render() { 
  var movie = MOCKED_MOVIES_DATA[0];  //获取首条数据
  return (
    <View style={styles.container}> 
      <Text>{movie.title}</Text>     //赋值
      <Text>{movie.year}</Text>
      <Image 
          source={{uri: movie.posters.thumbnail}}   //图片
          style={styles.thumbnail}     //样式
        />
    </View> ); }

var styles = StyleSheet.create({    //创建样式
    container: {
      flex:1,
      flexDirection: 'row',
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: '#F5FCFF',
        },
    thumbnail: {
      width: 53,
      height: 81,
        },
      });

flexDirection: 'row' 是横向布局,默认为垂直布局

从数据源获取数据

var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';  //JSON格式
class SampleAppMovies extends Component {
  constructor(props) {          //加载组件
      super(props); 
      this.state = { movies: null, //定义变量和初始化值
      };
      this.fetchData = this.fetchData.bind(this);   //函数绑定,类似于Python类中self
    }

  componentDidMount() {   //组件加载完成后自动调用,一种组件生命周期的方法。
      this.fetchData(); 
  }

  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        // 注意,这里使用了this关键字,为了保证this在调用时仍然指向当前组件,我们需要对其进行“绑定”操作
        this.setState({      //对当前组件定义的变量进行赋值,并完成后会重新触发一次render函数渲染
            movies: responseData.movies,
          });
        })
      .done();    //可以用来抛出异常,不会忽略
   }

  render() { 
    if(!this.state.movies){    //判断是否赋值成功
      return this.renderLoadingView();   //进入等待中
    }
    var movie = this.state.movie[0];    //只取出第一条数据
      return this.renderMovie(movie);    //进行视图渲染
   }

  renderLoadingView(){    //在数据加载完成前,都会触发此渲染
    return (
         <View style={styles.container}>
            <Text>
              正在加载中......
            </Text>
         </View>
      );
  }

  renderMovie(movie){
    return (
         <View style={styles.container}>
          <Image 
            source={{uri: movie.posters.thumbnail}}
            style ={styles.thumbnail}
            />
          <View style={styles.rightContainer}>
              <Text style={styles.title}>{movie.title}</Text>
            <Text style={styles.year}>{movie.year}</Text>
          </View>
      </View>
      );
  }

}

流程既是,加载组件,渲染,同时调用组件生命周期方法,进行变量赋值,setState赋值完成后触发再次渲染,完成视图。

多条数据使用列表视图(ListView)

此处只列出与单条数据的改动点。

Render函数:

 render() { 
    if(!this.state.loaded){    //通过标志位判断
      return this.renderLoadingView();   //进入等待中
    }
    //var movie = this.state.movie[0];    //此处进行修改
    return (
        <ListView      //listview上节中说到需要的两个属性
            dataSource={this.state.dataSource}    //数据源
            renderRow={this.renderMovie}    //渲染内容
            style={styles.ListView}
        />
     );
   }

组件加载:

  constructor(props) {          //加载组件
      super(props); 
      var t = new ListView.DataSource({
        rowHasChanged: (row1,row2) => row1 !== row2,});  //ListView组件必需的方法
    this.state = {
      dataSource: t,
      loaded: false,    //类似标志位,用于判断数据是否加载完成
    };
      this.fetchData = this.fetchData.bind(this);   //函数绑定,类似于Python类中self
    }

添加数据:

  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        // 注意,这里使用了this关键字,为了保证this在调用时仍然指向当前组件,我们需要对其进行“绑定”操作
        this.setState({      //对当前组件定义的变量进行赋值,并完成后会重新触发一次render函数渲染
            dataSource: this.state.dataSource.cloneWithRows(responseData.movies),  //赋值
              loaded:true,  //更换标志位,状态更新
          });
        })
      .done();    //可以用来抛出异常,不会忽略
   }

样式

  listView: { 
    paddingTop: 20,
    backgroundColor: '#F5FCFF',
  },
  rightContainer: {
    flex: 1,
  },
  title: {
    fontSize: 20,
    marginBottom: 8,
    textAlign: 'center',
  },
  year: {
    textAlign: 'center',
  },

注册

  AppRegistry.registerComponent('SampleAppMovies', () => SampleAppMovies);

提示

ES6语法
图片本地加载大小需要进行调整
网络图片必须手动确定大小。
在从数据源拉取数据时,渲染赋值未调整是数据源格式与模拟数据处的格式相同。
如果使用真机调试,网络数据需要联网。
添加导航器,搜索,加载更多,等更多功能,在官网Examples/Movies上。

相关文章

网友评论

      本文标题:学习React Native日记二,Movie Fetcher

      本文链接:https://www.haomeiwen.com/subject/bnqnjttx.html