原文連接:http://www.tinghaige.com/html
本着什麼都要攙和的原則,一塊兒來看看React Native是如何開發iOS APP。node
圍觀本文需自備Mac OSX
, XCode
, node
以及 npm
。react
作好準備以後,打開你的終端(或其餘命令行利器),鍵入下面命令:ios
npm install -g react-native-cli
和git
react-native init AwesomeProject
此時,咱們會看到一個名爲AwesomeProject
的文件夾,這就是工程文件的位置。使用XCode
打開AwesomeProject.xcodeproj
,並點擊RUN
,會看到iOS模擬器以及此項目對應的內容,效果以下:github
若是想要修改顯示內容,請打開index.ios.js
,裏面是一堆Javascript模樣的東西。修改以後,在iOS模擬器中cmd+R
就能夠看到修改後的效果。npm
接下來,咱們按照教程,來展現一張電影海報,爲了方便,咱們直接修改index.ios.js
。react-native
在var React = require('react-native');
後面,咱們先模擬一下海報所須要的數據:xcode
var MOCKED_MOVIES_DATA = [ {title: 'Title', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}}, ];
咱們須要展現電影的標題、年份以及縮略圖,所以咱們須要下面這些東西(看起來也不難理解):佈局
var { AppRegistry, Image, StyleSheet, Text, View, } = React;
下面,爲了展現咱們須要的內容,咱們來修改一下render
部分的內容。
render: function() { 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}} /> </View> ) }
最直觀的感覺,就像是咱們在Javascript代碼中寫了HTML代碼,<View>
看起來相似於<div>
。(此時在iOS模擬器中cmd+R
能夠看到不帶樣式的效果)
接下來,咱們爲渲染出來的數據添加樣式:
var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, thumbnail: { width: 53, height: 81, }, });
咱們可使用flex
來進行佈局,看起來是個好消息。
在這時候,教程說,海報圖片(<Image>
)尚未添加樣式,咱們找到<Image source={{uri: movie.posters.thumbnail}} />
,添加上style={styles.thumbnail}
也就是變成下面的樣子:
<Image source={{uri: movie.posters.thumbnail}} style={styles.thumbnail} />
此時在模擬器中cmd+R
,能夠看到效果以下:
這還沒完,咱們能夠以一種更優美的方式來展現電影的信息,就是下面這個結構:
+---------------------------------+ |+-------++----------------------+| || || Title || || Image || || || || Year || |+-------++----------------------+| +---------------------------------+
咱們只須要修改一下render
部分return
的內容以及樣式styles
的部份內容:
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> );
修改styles
中container
部分:
container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', },
在styles
中添加rightContainer
:
rightContainer: { flex: 1, },
樣式內容寫在styles
對象中,不要忘記寫,
。
下面優化一下年份和標題的樣式:
title: { fontSize: 20, marginBottom: 8, textAlign: 'center', }, year: { textAlign: 'center', },
此時在模擬器中cmd+R
,能夠看到效果以下:
下次咱們聊聊如何取回真實數據,固然,下次不必定是何時(LOL)。