簡(jiǎn)介
Facebook 在 React.js Conf 2015 大會(huì)上推出了基于 JavaScript 的開源框架 React Native
React Native 結(jié)合了 Web 應(yīng)用和 Native 應(yīng)用的優(yōu)勢(shì)谭梗,可以使用 JavaScript 來開發(fā) iOS 和 Android 原生應(yīng)用。在 JavaScript 中用 React 抽象操作系統(tǒng)原生的 UI 組件觅彰,代替 DOM 元素來渲染等赘艳。
環(huán)境搭建
對(duì)于Android開發(fā)者來說叛氨,只需要下載node和React Native即可(以下方案針對(duì)于mac)
下載node:
<pre>brew install node</pre>
下載React Native
<pre>npm install -g react-native-cli</pre>
新建React Native項(xiàng)目
<pre>react-native init HelloReact</pre>
項(xiàng)目介紹
Package.json
<pre>
{
"name": "HelloReact",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"react": "^15.0.2",
"react-native": "^0.26.2"
}
}
</pre>
這里主要放的配置瘪吏,跟Android的 build.gradle 文件差不多
Index.android.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class HelloReact extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
hello React
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('hello', () => HelloReact);
如果Android和ios的代碼是不相同的話铃彰,那就在各自的文件中編碼,如果相同的話歇式,可以把最后一行直響通用的component,減少代碼的重復(fù)編寫
簡(jiǎn)單介紹一下上面的代碼:
新建了一個(gè)HelloReact
- 新建HelloReact,繼承自Component(
- 在HelloReact中添加組件
- 然后去美化組件
- 最后最重要的一步注冊(cè)組件
AppRegistry.registerComponent('hello', () => HelloReact);
解釋一下這一行代碼胡野,第一個(gè)參數(shù)隨便寫材失,但是要跟android或者ios中相對(duì)應(yīng),Android中的MainActivity中有一個(gè)getMainComponentName方法硫豆,它的返回值要跟這里的第一個(gè)參數(shù)對(duì)應(yīng)龙巨,第二個(gè)要指向入口的Component
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "hello";
}
注:用到的組件都需要手動(dòng)去注冊(cè)笼呆,如:在HelloReact中用到Text,需要手動(dòng)在react-native中引入Text