React Native之this详解

this引起的错误详解

我们在学习React Native的过程中,肯定经常遇见过undefined is not an object这样的问题吧,尤其是刚开始学习的时候,使用this.props或者this.setState的时候会报类似于如下错误:

接下来我们来分析以下到底是什么原因造成的错误,

根据错误的提示,找到报错的代码,我们会发现:

报错的都是this.props.?或者this.setState(?),都是出现在有this的地方

报错的原因是没有定义该对象,而我们都知道this代表的就是当前对象,又怎么会出现未定义对象呢?那就只能说明是代表当前对象的this和此处this.props的this指代的不是同一个对象。

那么我们就需要弄明白,什么时候this指代的不是当前对象的this呢,接下里我们来看一个Demo,首先,我们分三处分别使用this,看一下是什么样的结果,如下:

class RN_This extends Component {

    constructor(props) {
        super(props)
        this.state = {
            name: ‘VennyChen‘,
            age: 24,
            sex: ‘男‘
        }
    }

    componentDidMount() {
        //第一处
        // this.showStudentName()
    }

    render() {
        //第二处
        this.showStudentName()
        return (
            <View style={styles.container}>
                <Head
                    onPress={this.showStudentName} text="this的第一种绑定方式">
                </Head>
            </View>
        )
    }

    showStudentName() {
        //第三处
        //alert(this.state.name)
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: ‘column‘,
        justifyContent: ‘center‘,
        alignItems: ‘center‘,
    }
})

module.exports = RN_This

运行的结果是:

第一处:正常执行

第二处:正常执行

第三处:undefined is not an object

由此可以看出,只要我们不在render函数的返回组件中使用this.props或者this.setState,那么this就作用于当前操作对象

于是就有人要问了,那我们如何在render函数的return中使用this.props或者this.setState呢?当然,就是接下来要讲的,React Native中绑定this的方法:

绑定this的三种方法

方法一:

在构造方法constrctor中绑定,绑定方式如下:

this.函数名 = this.函数名.bind(this)

完成代码如下:

import React, {Component} from ‘react‘
import {AppRegistry, StyleSheet, Image, View, Text} from ‘react-native‘
import Head from ‘../widget/Head‘

class RN_This extends Component {

    constructor(props) {
        super(props)
        this.state = {
            name: ‘VennyChen‘,
            age: 24,
            sex: ‘男‘
        }
        //第一种this的绑定方式
        this.showStudentName = this.showStudentName.bind(this)
    }

    render() {
        return (
            <View style={styles.container}>
                <Head onPress={this.showStudentName} txt="this的第一种绑定方式"></Head>
            </View>
        )
    }

    showStudentName() {
        alert(this.state.name)
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: ‘column‘,
        justifyContent: ‘center‘,
        alignItems: ‘center‘,
    }
})

module.exports = RN_This

方法二:在Render函数的组件中直接绑定,绑定方法如下:

{this.函数名.bind(this)}

完整代码如下:

import React, {Component} from ‘react‘
import {AppRegistry, StyleSheet, Image, View, Text} from ‘react-native‘
import Head from ‘../widget/Head‘

class RN_This extends Component {

    /*绑定this的三种实现方式*/

    constructor(props) {
        super(props)
        this.state = {
            name: ‘VennyChen‘,
            age: 24,
            sex: ‘男‘
        }
    }

    render() {
        return (
            <View style={styles.container}>
                {/*this的第二种绑定方式*/}
                <Head onPress={this.showStudentAge.bind(this)} txt="this的第二种绑定方式"></Head>
            </View>
        )
    }

    showStudentAge() {
        alert(this.state.age)
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: ‘column‘,
        justifyContent: ‘center‘,
        alignItems: ‘center‘,
    }
})

module.exports = RN_This

方法三:使用箭头函数,因为在ES6中,箭头函数是自己的this值的,所以箭头函数内的this值继承自外围作用域,因此,在箭头函数中是可以直接使用this的,如下:

import React, {Component} from ‘react‘
import {AppRegistry, StyleSheet, Image, View, Text} from ‘react-native‘
import Head from ‘../widget/Head‘

class RN_This extends Component {

    constructor(props) {
        super(props)
        this.state = {
            name: ‘VennyChen‘,
            age: 24,
            sex: ‘男‘
        }
    }

    render() {
        return (
            <View style={styles.container}>
                <Head onPress={this.showStudentSex} txt="this的第三种绑定方式"></Head>
            </View>
        )
    }

    /* this的第三种绑定方式,定义箭头函数*/
    showStudentSex = () => {
        alert(this.state.sex)
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: ‘column‘,
        justifyContent: ‘center‘,
        alignItems: ‘center‘,
    }
})

module.exports = RN_This
时间: 2024-08-29 01:35:07

React Native之this详解的相关文章

React Native通信机制详解

本文转载至 http://blog.cnbang.net/tech/2698/?from=groupmessage&isappinstalled=1 React Native是facebook刚开源的框架,可以用javascript直接开发原生APP,先不说这个框架后续是否能得到大众认可,单从源码来说,这个框架源码里有非常多的设计思想和实现方式值得学习,本篇先来看看它最基础的JavaScript-ObjectC通信机制(以下简称JS/OC). 概览 React Native用iOS自带的Java

React—组件生命周期详解

React-组件生命周期详解 转自 明明的博客  http://blog.csdn.net/slandove/article/details/50748473 (非原创) 版权声明:转载请注明出处,欢迎加入QQ群(115402375)讨论!博客编写已经转移到http://blog.csdn.net/limm33 在组件的整个生命周期中,随着该组件的props或者state发生改变,它的DOM表现也将有相应的改变,一个组件就是一个状态机,对于特定的输入,它总会返回一致的输出. React为每个组件

2019年17道高频React面试题及详解

以下面试题来源于github项目前端面试指南,那里有超过200道高频前端面试题及答案,目前拥有1400star. 为什么选择使用框架而不是原生?框架的好处: 组件化: 其中以 React 的组件化最为彻底,甚至可以到函数级别的原子组件,高度的组件化可以是我们的工程易于维护.易于组合拓展.天然分层: JQuery 时代的代码大部分情况下是面条代码,耦合严重,现代框架不管是 MVC.MVP还是MVVM 模式都能帮助我们进行分层,代码解耦更易于读写.生态: 现在主流前端框架都自带生态,不管是数据流管理

react.js 从零开始(四)React 属性和状态详解

属性的含义和用法: 1.属性的含义. props=properties 属性:一个事物的性质和关系. 属性往往与生俱来,不可以修改. 2. 属性的用法. <Helloworld name=??? /> 这个name 可以是 变量 ,对象,数组,函数表达式的值. var props={ a:1, b:2 } <Helloworld {...props} /> 这样react就会自动遍历props对象并添加到属性中去. 状态的含义和用法: 1.状态的含义. state 状态:事物所处的

Native Application 开发详解(直接在程序中调用 ntdll.dll 中的 Native API,有内存小、速度快、安全、API丰富等8大优点)

文章目录:                   1. 引子: 2. Native Application Demo 展示: 3. Native Application 简介: 4. Native Application 有何妙用: 5. MJ0011 关于 Native Application 的文章整理: 6. 互联网上其他关于 Native Application 的文章整理: 7. 小结: 1. 引子: 其实在好久以前就看了 MJ0011 翻译的那个<Native 应用程序详细>系列的文

React中的PropTypes详解

propTypes用来规范props必须满足的类型,如果验证不通过将会有warn提示. React PropTypes的种类有: React.PropTypes.array // 队列 React.PropTypes.bool.isRequired // Boolean 且必须 React.PropTypes.func // 函数 React.PropTypes.number // 数字 React.PropTypes.object // 对象 React.PropTypes.string //

React Native专题-江清清

本React Native讲解专题:主要讲解了React Native开发,由基础环境搭建配置入门,基础,进阶相关讲解. 刚创建的React Native交流8群:533435865  欢迎各位大牛,React Native技术爱好者加入交流!同时博客右侧欢迎微信扫描关注订阅号,移动技术干货,精彩文章技术推送! 关于React Native各种疑难杂症,问题深坑总结方案请点击查看: Mac和Windows安装搭建React Native环境教程如下: Mac OS X版本:Mac OS X安装R

React Native 从零到高级- 0基础学习路线

React Native QQ交流群(美团,饿了么,阿里的大神都在里面):576089067 React Native  从0 基础到高级 视频教程正在重录中,要了解最新进度可以关注菜鸟窝微信公众号(下图),旧版视频教程可以点击这里在线学习 学习路线(文章版),江清清老师出品,点击这里关注江清清 ,同时可以关注一下他的课程 基础入门:1.React Native For Android环境配置以及第一个实例2.React Native开发IDE安装及配置3.React Native应用设备运行(

React Native资料

React Native 环境搭建 React Native 配置和起步 Sublime Text 3 搭建 React.js 开发环境 集成 ReactNative集成到已有工程中-IOS React Native集成到现有项目(非cocoa pods) 语法 ES 6入门 ES6新特性概览 React入门教程 React中文网 React Native中文网 布局 Flex布局 Flex 布局教程:语法篇 Flex 布局教程:实例篇 混编 React Native构建本地视图组件 React