Android原生项目集成React Native

开发环境准备

首先按照开发环境搭建教程来安装React Native在安卓平台上所需的一切依赖软件(比如npm)。

在应用中添加JS代码

在项目的根目录中运行:

$ npm init
$ npm install --save react react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

npm init创建了一个空的node模块(其实就是创建了一个package.json描述文件),而npm install则创建了node_modules目录并把react和react-native下载到了其中。至于第三步curl命令,其实质是下载.flowconfig配置文件,这个文件用于约束js代码的写法。这一步非必需,可跳过。下面我们打开新创建的package.json文件,然后在其scripts字段中加入:

"start": "node node_modules/react-native/local-cli/cli.js start"

现在你的package.json内容应该类似这样:

{
  "name": "react-example",
  "version": "1.0.0",
  "description": "this is my first react example",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "keywords": [
    "react",
    "android",
    "example"
  ],
  "author": "max",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-native": "^0.42.3"
  }
}

接下来在项目根目录中创建index.android.js文件,然后将下面的代码复制粘贴进来:

'use strict';

import React from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class HelloWorld extends React.Component {
   
   
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.hello}>Hello, World</Text>
      </View>
    )
  }
}
var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  hello: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

AppRegistry.registerComponent('react-example', () => HelloWorld);
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值