[RN日志]React-Native 入门指南

一、背景

1、为什么需要React-Native?

在React-Native出现之前移动端主流的开发模式是原生开发和Hybrid开发(H5混合原生开发),Hybrid app相较于native app的优势是开发成本低开发速度快(H5页面开发跨平台,无需重新写web、android、ios代码),尽管native app在开发上需要更多时间,但却带来了更好的用户体验(页面渲染、手势操作的流畅性),也正是基于这两点Facebook在2015年推出了React-Native

What we really want is the user experience of the native mobile
platforms, combined with the developer experience we have when
building with React on the web.

上文摘自React-Native发布稿,React-Native的开发既保留了React的开发效率又拥有媲美原生的用户体验,其运行原理并非使用webview所以不属于Hybrid开发,想了解的可以查看React Native运行原理解析这篇文章。React-Native提出的理念是‘learn once,write every where’,之所以不是‘learn once, run every where’,是因为不同平台的用户体验有所不同,因此要运行全平台仍需要一些额外的适配,这里是Occhino对React-Native的介绍。
React-Native在Github的Star数
React-Native的npm下载数
上面两张图展示了React-Native的对于开发者的热门程度,且官方对其的开发状态一直更新,这也是其能抢占原生开发市场的重要因素。

二、搭建开发环境

在创建项目前我们需要先搭建React-Native所需的开发环境。
第一步需要先安装nodejs、python2、jdk8(windows有所不同,推荐使用macos开发,轻松省事)

brew install node //macos自带python和jdk

第二步安装React Native CLI

npm install -g react-native-cli

第三步安装Android Studio,参考官方的开发文档

三、创建第一个应用

使用react-native命令创建一个名为HelloReactNative的项目

react-native init HelloReactNative

等待其下载完相关依赖后,运行项目

react-native run-ios
or
react-native run-android

成功运行后的出现的界面是这样的

react-native-helloworld.png

四、基本的JSX和ES6语法

先看一下运行成功后的界面代码

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

const instructions = Platform.select({
    
    
    ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
    android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

//noinspection BadExpressionStatementJS
type
Props = {
    
    };
//noinspection JSAnnotator
export default class App extends Component<Props> {
    
    
    render() {
    
    
        return (
            <View style={
    
    styles.container}>
                <Text style={
    
    styles.welcome}>
                    Welcome to React Native!
                </Text>
                <Text style={
    
    styles.instructions}>
                    To get started, edit App.js
                </Text>
                <Text style={
    
    styles.instructions}>
                    {
    
    instructions}
                </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,
    },
});

代码中出现的importexportextendsclass以及未出现的() =>箭头函数均为ES6需要了解的基础语法,import表示引入需要的模块,export表示导出模块,extends表示继承自某个父类,class表示定义一个类,()=>为箭头函数,用此语法定义的函数带有上下文信息,因此不必再处理this引用的问题。
<Text style={styles.welcome}>Welcome to React Native!</Text>这段代码是JSX语法使用方式,和html标记语言一样,只不过这里引用的是React-Native的组件,Text是一个显示文本的组件,可以看到style={styles.welcome}这是JSX的另一个语法可以将有效的js表示式放入大括号内,Welcome to React Native!为其内容文本,可以尝试修改他的内容为Hello React Native!,刷新界面后
在这里插入图片描述
熟悉更多的ES6语法有助于更有效率的开发。

五、组件的属性和状态

在了解了一些基本的JSX和ES6语法后,我们还需要了解两个比较重要的概念即propsstateprops为组件的属性,state为组件的状态,两者间的区别在于,props会在组件被实例化时通过构造参数传入,所以props的传递为单向传递,且只能由父组件控制,state为组件的内部状态由组件自己管理,不受外界影响。propsstate都能修改组件的状态,两者的改变会导致相关引用的组件状态改变,也就是说在组件的内部存在子组件引用了propsstate,那么当发生改变时相应子组件会重新渲染,其实这里也可以看出propsstate的使用联系,父组件可以通过setState修改state,并将其传递到子组件的props中使子组件重新渲染从而使父组件重新渲染。

六、组件生命周期

在这里插入图片描述
组件的生命周期会经历三个阶段

Mounting:挂载
Updating:更新
Unmounting:移除

对应的生命周期回调方法为

componentWillMount()//组件将要挂载时调用
render()//组件渲染时调用
componentDidMount()//组件挂载完成时调用
componentWillReceiveProps(object nextProps)//组件props和state改变时调用
shouldComponentUpdate(object nextProps,object nextState)//返回false不更新组件,一下两个方法不执行
componentWillUpdate(object nextProps,object nextState)//组件将要更新时调用
componentDidUpdate(object nextProps,object nextState)//组件完成更新时调用
componentWillUnmount()//组件销毁时调用

这里我们需要重点关注的地方在于组件运行的阶段,组件每一次状态收到更新都会调用render()方法,除非shouldComponentUpdate方法返回false,可以通过此方法对组件做一些优化避免重复渲染带来的性能消耗。

样式
React-Native样式实现了CSS的一个子集,样式的属性与CSS稍有不同,其命名采用驼峰命名,对前端开发者来说基本没差。使用方式也很简单,首先使用StyleSheet创建一个styles

const styles = StyleSheet.create({
    
     
    container:{
    
    
        flex:1
    }
})

然后将对应的style传给组件的style属性,例如<View style={styles.container}/>

七、常用组件

在日常开发中最常使用的组件莫过于View,Text,Image,TextInput的组件。

View基本上作为容器布局,在里面可以放置各种各样的控件,一般只需要为其设置一个style属性即可,常用的样式属性有flex,width,height,backgroundColor,flexDirector,margin,padding更多可以查看Layout Props。

Text是一个显示文本的控件,只需要在组件的内容区填写文字内容即可,例如<Text>Hello world</Text>,可以为设置字体大小和颜色<Text style={ {fontSize:14,color:'red'}}>Hello world</Text>,同时也支持嵌套Text,例如

<Text style={
    
    {
    
    fontWeight: 'bold'}}>
        I am bold
        <Text style={
    
    {
    
    color: 'red'}}>
          and red
        </Text>
</Text>

TextInput是文本输入框控件,其使用方式也很简单

<TextInput
     style={
    
    {
    
    width:200,height:50}}
     onChangeText={
    
    (text)=>console.log(text)}
/>

style设置了他的样式,onChangeText传入一个方法,该方法会在输入框文字发生变化时调用,这里我们使用console.log(text)打印输入框的文字。

Image是一个图片控件,几乎所有的app都会使用图片作为他们的个性化展示,Image可以加载本地和网络上的图片,当加载网络图片时必须设定控件的大小,否则图片将无法展示

加载本地图片,图片地址为相对地址
<Image style={
    
    {
    
    width:100,height:100}} source={
    
    require('../images/img001.png')}/>
加载网络图片
<Image style={
    
    {
    
    width:100,height:100}} source={
    
    {
    
    uri:'https://facebook.github.io/react-native/docs/assets/favicon.png'}}/>

猜你喜欢

转载自blog.csdn.net/u013034585/article/details/106242866