ReactNative学习笔记十五之this的使用

作者: mymdeep | 来源:发表于2017-08-20 16:23 被阅读86次

    在刚开始接触ReactNative的时候出现的错误最多的是 :



    这是一个很常见的问题,问题的根源就是对this的理解不清楚。下面就会根据几个例子解释一下这个问题。

    bind(this)

    我们先看一个简单的例子:

    import React, { Component } from 'react';
    import {
        AppRegistry,
        StyleSheet,
        ToastAndroid,
        Text,
        TouchableOpacity,
        View
    } from 'react-native';
    
    export default class TestLayout extends Component {
        constructor(props) {
            super(props);
            this.state = {
                title:"aaaa"
            };
        }
        _onPressButton(){
            ToastAndroid.show(this.state.title, ToastAndroid.SHORT);
        }
        render() {
            return (
                <TouchableOpacity onPress={this._onPressButton}>
                    <Text>{"click"}</Text>
                </TouchableOpacity>
            );
        }
    }
    
    AppRegistry.registerComponent('TestLayout', () => TestLayout);
    

    我们在点击事件_onPressButton中使用了this,但是此时会报一个错误:


    这是为什么呢?
    原因就是在方法_onPressButton中使用的this是指_onPressButton本身,并不是当前的Component。
    那么如何在方法中使用Component的this呢?
    很简单,使用bind(this),即:
      render() {
            return (
                <TouchableOpacity onPress={this._onPressButton.bind(this)}>
                    <Text>{"click"}</Text>
                </TouchableOpacity>
            );
        }
    

    此时在运行,发现报错没有了,程序可以正常运行了。

    this在方法中的使用

    更改代码如下:

      _onPressButton(){
           this._print("bbbb")
        }
        _print(data){
            ToastAndroid.show(this.state.title+data, ToastAndroid.SHORT);
        }
    

    发现没有使用bind(this)仍然是可以使用的。
    除此之外,在如下的情况下,仍然是可以使用的:

        _onPressButton(){
          this._print((data)=>{ToastAndroid.show(this.state.title+data, ToastAndroid.SHORT);
          })
    
        }
        _print(callback){
            callback("bbbb")
        }
    

    不用使用bind

    上面介绍了bind(this)的使用,如果使用的是ES6标准不想使用bind(this),也是可以的,使用箭头函数即可:

      _onPressButton = () =>{
            ToastAndroid.show(this.state.title, ToastAndroid.SHORT);
                }
    
        render() {
            return (
                <TouchableOpacity onPress={this._onPressButton}>
                    <Text>{"click"}</Text>
                </TouchableOpacity>
            );
        }
    

    总结

    本文内容较少,但是在实际应用中还是较为广泛的。总体来说,在React Native开发中,如果使用ES6语法的话,最好绑定this.但是使用ES5语法的话不需要绑定this.因为ES5会autobinding。this所指的就是直至包含this指针的上层对象。如果使用ES6编码 且 自定义方法里面需要使用到this .这时需要绑定this,否则报错。


    之前文章合集:
    Android文章合集
    iOS文章合集
    ReactNative文章合集
    如果你也做ReactNative开发,并对ReactNative感兴趣,欢迎关注我的公众号,加入我们的讨论群:

    相关文章

      网友评论

        本文标题:ReactNative学习笔记十五之this的使用

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