一、简介
React中定义一个组件,可以通过ES6版本以前的React.createClass或者ES6的class xxx extends React.Component。如果使用ES6并且react版本在16以上,推荐采用class的方式,代码结构更加清晰,可读性强,而且React官方也推荐使用这种方式定义组件。
绑定this是react中非常重要的一部分。React中,绑定this的方式有多种,下面一一看看怎么进行this绑定。
二、 方法
a.【第一种方式】使用ES5方式创建组件绑定this的方法
如果你使用的是React 15及以下的版本,你可能使用过React.createClass函数来创建一个组件。你在里面创建的所有函数的this将会自动绑定到组件上。
/**
* @Description: 第一种方法: 使用ES5方式创建组件绑定this的方法
* @author weishihuai
* @date 2019/5/15 9:59
*
* 说明: React.createClass is deprecated since React 15.5.0, use the npm module create-react-class instead (react/no-deprecated)
* 注意随着React 16版本的发布官方已经将改方法从React中移除
*
*/
const MyApp1 = React.createClass({
handleClickListener() {
console.log('this > ', this); // this 指向App组件本身
},
render() {
return (
<div onClick={this.handleClickListener}>使用ES5方式创建组件绑定this的方法</div>
);
}
});
export default MyApp1;
b.【第二种方式】render方法调用的时候使用.bind(this)进行绑定
import React from 'react';
/**
* @Description: 第二种方法: render方法调用的时候使用.bind(this)进行绑定
* @author weishihuai
* @date 2019/5/15 9:59
*
* 说明: 由于组件每次执行render会重新分配事件函数,将会影响性能
*/
export default class MyApp2 extends React.Component {
handleClickListener() {
console.log('this->', this);
}
render() {
return (
<div onClick={this.handleClickListener.bind(this)}>
render方法调用的时候使用.bind(this)进行绑定
</div>
);
}
}
缺点:由于组件每次执行render会重新分配事件函数,将会影响性能
c.【第三种方式】render方法调用的时候使用箭头函数进行绑定
/**
* @Description: 第三种方法: render方法调用的时候使用箭头函数进行绑定
* @author weishihuai
* @date 2019/5/15 9:59
*
* 说明: 由于组件每次执行render会重新分配事件函数,将会影响性能
*/
export default class MyApp3 extends React.Component {
handleClickListener() {
console.log('this->', this);
}
render() {
return (
<div onClick={e => this.handleClickListener(e)}>
render方法调用的时候使用箭头函数进行绑定
</div>
);
}
}
这种方式使用了ES6的上下文绑定来让this指向当前组件,同第二种方式,由于组件每次执行render会重新分配事件函数,将会影响性能。
d.【第四种方式】在构造函数中进行显式绑定this.xxx.bind(this)
为了避免在render中绑定this引发可能的性能问题,我们可以在constructor中预先进行绑定。
import React from 'react';
/**
* @Description: 第四种方法: 在构造函数中进行显式绑定this.xxx.bind(this)
* @author weishihuai
* @date 2019/5/15 9:59
*
* 说明: 如果有多个函数需要写很多重复绑定代码
*/
export default class MyApp4 extends React.Component {
constructor(props) {
super(props);
this.handleClickListener = this.handleClickListener.bind(this);
}
handleClickListener() {
console.log('this->', this);
}
render() {
return (
<div onClick={this.handleClickListener}>
在构造函数中进行显式绑定 this.xxx = this.xxx.bind(this)
</div>
);
}
}
缺点:如果有多个函数需要写很多重复绑定代码,可读性和可维护性相对较差。
e.【第五种方式】在定义函数的时候使用箭头函数定义
import React from 'react';
/**
* @Description: 第五种方法: 在定义函数的时候使用箭头函数定义
* @author weishihuai
* @date 2019/5/15 9:59
*
* 说明: 箭头函数会自动绑定到当前组件的作用域中
* 如果使用ES6和React 16以上的版本,强烈推荐使用该方式进行绑定
*/
export default class MyApp5 extends React.Component {
handleClickListener = () => {
console.log('this->', this);
};
render() {
return (
<div onClick={this.handleClickListener}>
在定义函数的时候使用箭头函数定义
</div>
);
}
}
优点:箭头函数会自动绑定到当前组件的作用域中,不会产生很多重复代码,推荐使用此种方式绑定this.
三、总结
以上就是关于在React中绑定this的5中方法介绍,为了后期代码的可读性以及可维护性,推荐大家都使用箭头函数定义函数的方式进行绑定,当然特殊需求,就需要根据具体需求选择合适的方式绑定。本文只是笔者的一些学习总结,希望能对大家的学习有所帮助。