前言
眼看很多公司都開始嘗試使用ReactNative,達到跨平臺開發,最近也寫了很多文章,希望讓更多想了解的同學快速上手ReactNative.
如果喜歡我的文章,可以關注我微博:袁崢Seemygo
ReactNative之項目結構介紹
- 一、初始化ReactNative工程
- 自動創建iOS和安卓工程,和對應的JS文件,index.ios.js,index.android.js
- 并且通過Npm加載package.json中描述的第三方框架,放入node_modules文件夾中
react-native init ReactDemo
- 二、打開iOS工程,找到AppDelegate.m文件,查看程序啟動完成
- 注意:加載控件方法(initWithBundleURL:moduleName:initialProperties:launchOptions:)
-
moduleName
不能亂傳,必須跟js文件中注冊的模塊名字保持一致
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
// 1.獲取js文件url
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
// 2.加載控件
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"ReactDemo"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
// 3.創建窗口
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
// 4.設置窗口根控制器的View
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
// 5.顯示窗口
[self.window makeKeyAndVisible];
return YES;
}
-
三、打開index.ios.js文件,使用webStorm打開。webStorm代碼提示
- iOS程序一啟動,就會加載這個文件,去創建組件,并且把加載完的組件顯示到界面上
-
index.ios.js實現步驟
- 1.加載React模塊,因為需要用到JSX,加載Compoent,需要用到里面的Compoent組件
- React默認組件,Compoent非默認組件,都在react文件夾中。
- 2.加載AppRegistry,StyleSheet,Text,View原生組件,在react-native文件夾中
- 3.自定義組件,作為程序入口組件
- 4.創建樣式表
- 5.注冊組件,程序入口,程序一啟動就會自動加載注冊組件.
- 1.加載React模塊,因為需要用到JSX,加載Compoent,需要用到里面的Compoent組件
// 1.加載React,Componet組件
import React,{compoent} from 'react'
// 2.加載原生組件
import
{
AppRegistry,
StyleSheet,
View,
Text
}
from 'react-native'
// 3.自定義組件,作為程序入口組件
export default class ReactDemo extends Component {
// 當加載組件的時候,就會調用render方法,去渲染組件
render(){
return (
<View style={styles.mainStyle}>
</View>
)
}
}
// 4.創建樣式表
// 傳入一個樣式對象,根據樣式對象中的描述,創建樣式表
var styles = Stylesheet.create({
mainStyle:{
flex:1,
backgroundColor:'red'
}
})
// 5.注冊組件,程序入口
// 第一個參數:注冊模塊名稱
// 第二個參數:函數, 此函數返回組件類名, 程序啟動就會自動去加載這個組件
AppRegistry.registerComponent('ReactDemo',()=>ReactDemo)
ReactNative語法
- 對于第一次接觸ReactNative的同學,最痛苦的是什么時候使用{},什么時候使用(),當然我也經歷過那段時間,為此簡單總結了下。
- ReactNative中,使用表達式的時候需要用{}包住
style={styles.mainStyle}
- ReactNative中,在字符串中使用變量的時候,需要用{}包住
var str = 'hello'
<Text>{str}</Text>
- ReactNative中,對象,字典需要用{}包住
- style = {},最外層表達式,用{}包住
- {flex:1},對象,用{}包住
<View style={{flex:1}}></View>
- 創建組件<View></View>,必須要用()包住
- 因此只要返回組件,都需要用()
render(){
return (
<View style={styles.mainStyle}>
</View>
)
}