React Native 系列(二)

时间:2017-08-25 00:55:15   收藏:0   阅读:341

前言

本系列是基于React Native版本号0.44.3写的,最初学习React Native的时候,完全没有接触过ReactJS,本文的目的是为了给那些JSReact小白提供一个快速入门,让你们能够在看React Native语法的时候不那么费劲,有过前端开发经验的可以直接忽略。

什么是React

React是一个JavaScript框架,用来开发web应用。Web应用开发中,比较流行的有三个框架:

从名字上,就能看到react native是基于React(都是Facebook出品)。React的设计思想是:

JSX

JSXJavaScript语言的扩展,它并不改变JS本身语法。使用起来类型XMLReact会对JSX的代码进行编译,生成JavaScript代码,用来描述React中的Element如何渲染。

上篇文章创建的项目中,index.ios.js里面的这段代码就是JSX语法:

render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
      </View>
    );
  }

其中,

<Text style={styles.welcome}>
    Welcome to React Native!
</Text>

会被编译成

React.createElement(
    Text,
    {style: styles.welcom},
    ‘Welcome to React Native!‘
)

注意:使用JSX,一定要在scope中,能够访问到React和对应的Element。比如刚刚的例子,在代码的最上面看到了这样的import

import React, { Component } from ‘react‘;
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableHighlight
} from ‘react-native‘;

tips: jsx编译结果在线查看
如果你的标签是空的,可以用/>进行close,比如:
<CustomComponent style={styles.welcome} />

大小写

JSX对大小写开头是敏感的

所以,自定义的component必须是大写字母开头

举个??:
如果上文中的Text改成小写,

<text style={styles.welcome}>
    Welcome to React Native!
</text>

会被编译成:

React.createElement(
    "text",
    { style: styles.welcome },
    "Welcome to React Native!"
);

React在解析的时候,会认为这和div类似,是html内置标签,引起错误。

JS代码

JSX中的JS表达式要用{}括起来,不要加引号,加引号后React会认为是字符串。
比如,你可以这么写:

<Text style={styles.welcome}>
    {"Welcome" + "to" + "React Native"}
</Text>

Children

根据以下的代码:

<View style={styles.container}>
    <Text style={styles.welcome}>
        Welcome to React Native!
    </Text>
</View>

可以看出,在JSX中可以嵌套Element形成一种层次结构,这种层次结构可以动态生成,例如:

render() {
    var textElement = <Text style={styles.welcome}>{mainText}</Text>

    return (
        <View style={styles.container}>
          {textElement}
        </View>
    );
  }

Element

Element是你在屏幕上想看到的东西,在React中,一个element就是一个对象。

React中,element是不变的。如果用户想要看到变化,就需要渲染下一帧。

那么你可能会问,这样效率不是很低么?

事实上,React只会更新变化的部分,对于不变的视图,是不会重新渲染的。

React强调函数式编程,不可变状态是函数式编程的核心思想之一。不可变状态能够让你的代码更容易编写,测试和维护。一个不可变的函数,在输入一定的时候,输出一定是一样的。

Component

React Native开发中,component是一个非常重要的概念,它类似于iOSUIView或者Android中的view,将视图分成一个个小的部分。
React Native中,我们通常采用ES6 class来定义一个Component

比如上面的代码:

export default class Hello extends Component {
    render(){
        // ...
    }
}

其中,render()是实际的渲染函数,通常,使用JSX来返回想要看到的视图。
React Native中的Component都是原生的Component,通过JS bridge来调用原生的Component来渲染。
这些Component分为两种:

  1. iOS/Android通用的,比如:NavigatorTextImage等等;
  2. 平台独有的,比如:NavigatorIOSProgressBarAndroid等等;

State/props

ReactComponent有两个内置参数对象

初始化

比如,我们对本文代码进行修改,新建一个Component:

class Scott extends Component {
  render(){
    return (
        <Text style={styles.welcome}>
            欢迎来到{this.props.name}博客学习RN
        </Text>
    );
  }
}

然后,我们使用这个自定义的Component

export default class Hello extends Component {
  render() {
    return (
        <View style={styles.container}>
            <Scott name={"scott"}/>
        </View>
    );
  }
}

保存文件,选中模拟器,command + R刷新一下,就能看到如下界面:
技术分享

通过这个例子,如何对Component初始化进行传值就已经很清楚了:

修改视图状态

React中,修改视图状态是通过this.setState触发render重新调用,进而修改视图状态。

我们继续修改上述代码,添加一个构造函数,对state进行初始化,然后在Scott初始化的时候,通过this.state.name获取到值。
在最上面的import中,我们导入TouchableOpacity,然后在点击事件中,我们调用this.setState更新显示的文字:

export default class Hello extends Component {

  // 构造
  constructor(props) {
    super(props);
    // 初始状态
    this.state = {name: "Jack"};
  }

  _onPressText(){
    this.setState({name: "scott"})
  }

  render() {
    return (
        <View style={styles.container}>
          <TouchableOpacity onPress={() => this._onPressText()}>
            <Scott name={this.state.name}/>
          </TouchableOpacity>
        </View>
    );
  }
}

保存,选中模拟器,command + R刷新一下,点击屏幕文字,效果如下:
技术分享

setState 注意事项

组件生命周期

技术分享

创建阶段

tip:**注意点constructorcomponentWillMountcomponentDidMount只会调用一次**

更新阶段

tips:注意点:绝对不要在componentWillUpdatecomponentDidUpdate中调用this.setState方法,否则将导致无限循环调用,在componentWillReceivePropsshouldComponentUpdate可以。

销毁阶段

举个例子

我们依旧修改以前的代码,给Scott这个Component添加上这些方法,最后代码是这样:

class Scott extends Component {

    // 构造
    constructor(props) {
        super(props);

        console.log("constructor")
    }

    componentWillMount() {
        console.log("componentWillMount")
    }

    componentDidMount() {
        console.log("componentDidMount")
    }

    shouldComponentUpdate() {
        console.log("shouldComponentUpdate")
        return true
    }

    componentWillReceiveProps() {
        console.log("componentWillReceiveProps")
    }

    componentWillUpdate(){
        console.log("componentWillUpdate")
    }

    componentDidUpdate() {
        console.log("componentDidUpdate")
    }

    componentWillUnmount() {
        console.log("componentWillUnmount")
    }

    render() {
        console.log("render")
        return (
            <Text style={styles.welcome}>
                点击注意看Lucy是否变成Scott:
                {this.props.name}
            </Text>
        );
    }
}

export default class Hello extends Component {

    // 构造
    constructor(props) {
        super(props);

        // 初始状态
        this.state = {firstName:"Lucy", lastName:"Tom"};
        this._onPressText = this._onPressText.bind(this);
    }


    _onPressText(){
        this.setState({firstName:"Scott"})
    }


    render() {
        return (
            <View style={styles.container}>
                <TouchableOpacity onPress={this._onPressText}>
                    <Scott name={this.state.firstName + this.state.lastName}/>
                </TouchableOpacity>
            </View>
        );
    }
}

保存代码,选择模拟器,command + R刷新一下界面,然后到Xcode控制台看输出结果,应该是如下图:
技术分享

我们点击屏幕,触发一下更新,然后可以看到控制台输出结果:
技术分享

tips: xcode控制台会每隔一秒输出__nw_connection_get_connected_socket_block_invoke 2 Connection has no connected handler, 解决办法:edit scheme -> Run -> Arguments -> Environment Variables -> Add -> Name: "OS_ACTIVITY_MODE"Value:"disable"

致谢

如果发现有错误的地方,欢迎各位指出,谢谢!

原文:http://www.cnblogs.com/yujihaia/p/7425870.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!