第一个RN应用(漂亮的首页和讲笑话列表)
对于不想折腾Android(or Kotlin)的Phper来说,要写app,RN真的是个不错的选择。
开发环境就不多说了,用npm轻松搞定,容易被墙,自行解决。
先看下目录结构吧:
index.android.js里面import './App',App.js里面处理首页展示跟逻辑:
import React, {Component} from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, TouchableOpacity, StatusBar, } from 'react-native'; import { StackNavigator } from 'react-navigation'; import Joke from './components/Joke'; export default class HomeScreen extends Component { static navigationOptions = { title: 'Welcome', }; render() { return ( <View style={styles.container}> <StatusBar backgroundColor="blue" barStyle="light-content"/> <Image source={require('./images/sh.jpeg')} style={styles.img}/> <Text style={styles.mid}>Purelightme && TT</Text> <TouchableOpacity onPress={()=>this.props.navigation.navigate('Joke',{ user: '亭亭'})} title="Joke time"><Text style={styles.btn}>开启奇幻之旅</Text></TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white' }, img: { width: 240, height: 240, borderWidth: 2, borderColor: '#ee735c', borderRadius: 120, opacity: 0.9, }, mid: { marginTop: 50, //transform: [{scale:2},{rotateX:'120deg'}] }, btn: { height: 25, marginTop: 40, borderWidth: 2, borderStyle: 'dotted', borderColor: 'gray', borderRadius: 2, textAlign: 'center', lineHeight: 25, } }); const FirstApp = StackNavigator({ Home: { screen: HomeScreen}, Joke: { screen: Joke}, }); AppRegistry.registerComponent('FirstApp', () => FirstApp);
Joke组件在components下的Joke.js:
import React, {Component} from 'react'; import { View, Text, StyleSheet, ListView, } from 'react-native'; import TWebView from 'components/TWebView'; class Joke extends Component { constructor(props) { super(props); this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), loaded: false, } } componentDidMount() { this._getJoke(); } static navigationOptions = { title: '讲个笑话', }; _getJoke() { fetch('https://v.juhe.cn/joke/randJoke.php?key=e3f934b3cee28f02ea95eb17044e0cd0') .then((response) => response.json()) .then((responseJson) => { this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseJson.result), loaded: true, }) }) .catch((error) => { console.error("出错啦!"); console.error(error); }); } _renderJoke(joke) { return ( <View style={styles.container}> <Text style={styles.content}>{joke.content}</Text> </View> ); } render() { if (!this.state.loaded) { return ( <View style={styles.container}> <Text>数据正在加载中</Text> </View> ); } return ( <ListView dataSource={this.state.dataSource} renderRow={this._renderJoke} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white' }, content: { marginTop: 10, }, }); module.exports = Joke;
主要用到了RN的StackNavigator,ListView,Image和Text就不说啦,fetch发起网络请求,数据来自聚合数据,后面打算结合百度AI的语音转换实现自动播放笑话,sounds good! nice RN.