初识React Native

简介

Facebook 在 React.js Conf 2015 大会上推出了基于 JavaScript 的开源框架 React Native

React Native 结合了 Web 应用和 Native 应用的优势,可以使用 JavaScript 来开发 iOS 和 Android 原生应用。在 JavaScript 中用 React 抽象操作系统原生的 UI 组件,代替 DOM 元素来渲染等。

环境搭建

对于Android开发者来说,只需要下载node和React Native即可(以下方案针对于mac)

下载node:
<pre>brew install node</pre>

下载React Native
<pre>npm install -g react-native-cli</pre>

新建React Native项目
<pre>react-native init HelloReact</pre>

项目介绍

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,减少代码的重复编写

简单介绍一下上面的代码:
新建了一个HelloReact

  1. 新建HelloReact,继承自Component(
  2. 在HelloReact中添加组件
  3. 然后去美化组件
  4. 最后最重要的一步注册组件

AppRegistry.registerComponent('hello', () => HelloReact);
解释一下这一行代码,第一个参数随便写,但是要跟android或者ios中相对应,Android中的MainActivity中有一个getMainComponentName方法,它的返回值要跟这里的第一个参数对应,第二个要指向入口的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";
    }

注:用到的组件都需要手动去注册,如:在HelloReact中用到Text,需要手动在react-native中引入Text

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 179,271评论 25 708
  • 持续更新中...... 一套企业级的 UI 设计语言和 React 实现。 https://mobile.ant....
    日不落000阅读 6,069评论 0 35
  • React Native优秀博客,以及优秀的Github库列表(很多英文资料源自于[awesome-react-n...
    董董董董董董董董董大笨蛋阅读 11,018评论 4 162
  • 落尽三千烦恼丝, 自此不问红尘事。 一身淄衣青山囚, 古佛青灯伴余生。 注释:这几句话是我心中的一种烦闷,因为一些...
    谭惜言阅读 1,671评论 0 2
  • 2017-01-28 华杉 上节刚说《传习录》主要是讲四书,今天这句,就出了四书的范围。四书之前一直在学,出了四书...
    郁萍阅读 1,678评论 0 0

友情链接更多精彩内容