美文网首页iOS
React Native学习笔记01

React Native学习笔记01

作者: 诸葛云纹 | 来源:发表于2017-01-11 18:11 被阅读20次

参考RN中文官网

集成React Native

一般来讲在命令行中直接输入react-native init 项目名称后,会自动新建相应的js文件。
若是已有项目需要新增RN界面等,需要以下步骤:

1.1 package.json

在项目根目录[1]下创建并编写package.json文件,然后终端运行npm install即可。

//package.json文件的书写示例
{
  "name": "项目名称",
  "version": "0.0.1",//版本号
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "react": "15.4.1",//react版本
    "react-native": "0.39.2"//RN版本
  }
}

1.2 Podfile

使用cocoapods安装依赖库。
可用依赖库可以在node_modules/react-native/React.podspec中查看。

//Podfile文件的书写示例
# target的名字一般与你的项目名字相同
target '项目的target' do

  # 'node_modules'目录一般位于根目录中
  # 但是如果你的结构不同,那你就要根据实际路径修改下面的`:path`
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'RCTText',
    'RCTNetwork',
    'RCTWebSocket', # 这个模块是用于调试功能的
    # 在这里继续添加你所需要的模块
  ]

end

1.3 index.ios.js

在根目录下创建index.ios.js文件,并书写自己的React Native代码,这里暂不说明,之后会详细介绍

1.4 原生代码

RCTRootView导入

//RCTRootView初始化示例
//注意这里只是生成了一个UIView类,而非UIViewController类
  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"AwesomeProject"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

1.5 Packager

运行Packager
在项目根目录下,终端输入npm start

1.6 start

运行程序

index.ios.js基本书写方式

2.1 index.ios.js

//index.ios.js书写示例
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
  //这里添加你需要的组件
} from 'react-native';

//此处类名至少有一个应与最后注册时一致,以做入口
class HelloWorld extends Component {
  render() {
    return (
    //此处为最终该对象获得的视图,只能获得单视图,多视图使用如下示例进行嵌套返回
    <View>
        <Text>Hello world!</Text>
        <Text>Good Morning</Text>
        <Text>中文也是可以的</Text>
        <Text>balabalabala</Text>
    </View>
    );
  }
}

// 注意,这里用引号括起来的'HelloWorldApp'必须和你init创建的项目名一致
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorld);

2.2 JSX知识

请注意下列代码中{pic}外围有一层括号,我们需要用括号来把pic这个变量嵌入到JSX语句中。括号的意思是括号内部为一个js变量或表达式,需要执行后取值。因此我们可以把任意合法的JavaScript表达式通过括号嵌入到JSX语句中。

let pic = {
      uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
};
return (
      <Image source={pic} style={{width: 193, height: 110}} />
);

style本身一个整体,定义内容样式,若是单独的直接定义样式,则需要两层{},若是使用StyleSheet方式,则只用一层{}.

flexDirection布局主轴方向:竖直轴(默认)column,水平轴row,column-reverse,row-reverse

justifyContent布局主轴对齐方式:center,flex-end,flex-start,space-around,space-between

alignItems布局次轴对齐方式:auto,center,flex-end,flex-start,stretch[2]

未完待续


  1. 这里的根目录不存在Xcode项目文件(.xcodeproj)。

  2. 要使stretch选项生效的话,子元素在次轴方向上不能有固定的尺寸。

相关文章

网友评论

    本文标题:React Native学习笔记01

    本文链接:https://www.haomeiwen.com/subject/qburbttx.html