首页 > 其他 > 详细

React组件绑定this的四种方式

时间:2019-03-12 20:31:55      阅读:131      评论:0      收藏:0      [点我收藏+]

技术分享图片

题图 By HymChu From lnstagram

 

用react进行开发组件时,我们需要关注一下组件内部方法this的指向,react定义组件的方式有两种,一种为函数组件,一种为类组件,类组件内部可以定义一些方法,这些方法的this需要绑定到组件实例上,小编这里总结了一下,一共有四种方案:

第一种方案,在构造函数内部使用bind绑定this,这样做的好处是,避免每次渲染时都要重新绑定,代码如下:

 

import React, {Component} from ‘react‘?class Test extends React.Component {    constructor (props) {        super(props)        this.state = {message: ‘Allo!‘}        this.handleClick = this.handleClick.bind(this)    }?    handleClick (e) {        console.log(this.state.message)    }?    render () {        return (            <div>                <button onClick={ this.handleClick }>Say Hello</button>            </div>        )    }}

 

第二种方案同样是用bind,但是这次不再构造函数内部使用,而是在render函数内绑定,但是这样的话,每次渲染都需要重新绑定,代码如下:

 

import React, {Component} from ‘react‘?class Test extends React.Component {    constructor (props) {        super(props)        this.state = {message: ‘Allo!‘}    }?    handleClick (name, e) {        console.log(this.state.message + name)    }?    render () {        return (            <div>                <button onClick={ this.handleClick.bind(this, ‘赵四‘) }>Say Hello</button>            </div>        )    }}

 

第三种方案是在render函数中,调用方法的位置包裹一层箭头函数,因为箭头函数的this指向箭头函数定义的时候其所处作用域的this,而箭头函数在render函数中定义,render函数this始终指向组件实例,所以箭头函数的this也指向组件实例,代码如下:

 

class Test extends React.Component {    constructor (props) {        super(props)        this.state = {message: ‘Allo!‘}    }?    handleClick (e) {        console.log(this.state.message)    }?    render () {        return (            <div>                <button onClick={ ()=>{ this.handleClick() } }>Say Hello</button>            </div>        )    }

 

以上这种方式有个小问题,因为箭头函数总是匿名的,如果你打算移除监听事件,是做不到的,那么怎么做才可以移除呢?看下一种方案。

 

第四种方案,代码如下:

 

class Test extends React.Component {    constructor (props) {        super(props)        this.state = {message: ‘Allo!‘}    }    handleClick = (e) => {        console.log(this.state.message)    }    render () {        return (            <div>                <button onClick={ this.handleClick }>Say Hello</button>            </div>        )    }}

 

不过,在Classes中直接赋值是ES7的写法,ES6并不支持,你有两种选择,一种是配置你的开发环境支持ES7,一种使采用如下方式,下面这种方式是第四种方案的另外一种写法,代码如下:

 

class Test extends React.Component {    constructor (props) {        super(props)        this.state = {message: ‘Allo!‘}        this.handleClick = (e) => {            console.log(this.state.message)        }    }    render () {        return (            <div>                <button onClick={ this.handleClick }>Say Hello</button>            </div>        )    }?

 

以上便是react组件内部方法this绑定的四种方案,如果还有其它方案欢迎留言。

 

资料引用:

https://blog.csdn.net/sinat_17775997/article/details/56839485

 

更多干货关注下方公众号

技术分享图片

欢迎关注、转发、点击好看

 

React组件绑定this的四种方式

原文:https://www.cnblogs.com/suoking/p/10519406.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!