一、代码结构
不同于mac开发环境,拥有index.ios.js和index.android.js两个编译文件,此处windows下仅在app.js中编译;
二、简单的helloword一闪闪效果
app.js
import React, { Component } from 'react'; import { Text, View, StyleSheet } from 'react-native'; class HelloWorldApp extends Component { constructor(props) { super(props); this.state = { showText: true }; // 每1000毫秒对showText状态做一次取反操作 setInterval(() => { this.setState(previousState => { return { showText: !previousState.showText }; }); }, 1000); } render() { // 根据当前showText的值决定是否显示text内容 let display = this.state.showText ? this.props.text : ' '; return ( <View> <Text style={[styles.bigblue, {color: 'red'}]}>{display}</Text> </View> ); } } export default class App extends Component { render() { return ( <View> <HelloWorldApp text='Hello world' /> </View> ); } } const styles = StyleSheet.create({ bigblue: { color: 'blue', fontWeight: 'bold', fontSize: 30, } });
三、涉及知识点
多用es6语法、react语法、jsx语法和RN语法及开发思想(组件化)等等。RN运行环境:移动端(真机或模拟器)。
四、电影列表demo
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, { Component } from "react"; import { Image, FlatList, StyleSheet, Text, View } from "react-native"; var REQUEST_URL = "https://raw.githubusercontent.com/facebook/react-native/0.51-stable/docs/MoviesExample.json"; type Props = {}; export default class App extends Component { constructor(props) { super(props); this.state = { data: [], loaded: false }; // 在ES6中,如果在自定义的函数里使用了this关键字,则需要对其进行“绑定”操作,否则this的指向会变为空 // 像下面这行代码一样,在constructor中使用bind是其中一种做法(还有一些其他做法,如使用箭头函数等) this.fetchData = this.fetchData.bind(this); } componentDidMount() { this.fetchData(); } fetchData() { fetch(REQUEST_URL) .then(response => response.json()) .then(responseData => { // 注意,这里使用了this关键字,为了保证this在调用时仍然指向当前组件,我们需要对其进行“绑定”操作 this.setState({ //这里使用了数组的 concat 方法生成新数组,不能直接在原数组上 push! data: this.state.data.concat(responseData.movies), loaded: true, }); }); } render() { if (!this.state.loaded) { return this.renderLoadingView(); } return ( <FlatList data={this.state.data} renderItem={this.renderMovie} style={styles.list} keyExtractor={item => item.id} /> ); } renderLoadingView() { return ( <View style={styles.container}> <Text> 正在加载电影数据…… </Text> </View> ); } renderMovie({ item }) { // { item }是一种“解构”写法,请阅读ES2015语法的相关文档 // item也是FlatList中固定的参数名,请阅读FlatList的相关文档 return ( <View style={styles.container}> <Image source={{ uri: item.posters.thumbnail }} style={styles.thumbnail} /> <View style={styles.rightContainer}> <Text style={styles.title}>{item.title}</Text> <Text style={styles.year}>{item.year}</Text> </View> </View> ); } } var styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, rightContainer: { flex: 1, }, list: { paddingTop: 20, backgroundColor: '#F5FCFF', }, thumbnail: { marginLeft: 20, 53, height: 81 }, title: { fontSize: 20, marginBottom: 8, textAlign: 'center', }, year: { textAlign: 'center', } });