React中经常用到的类属性到底是什么

React组件形式有两种,一种是function component,另一种写法是class component。在写class component时,我们经常会这么写

class PersonForm extends React.Component{
	constructor(props){
		super(props);
		this.handleClick = this.handleClick.bind(this)
	}
	handleClick(){
		console.log(this)
	}
	render(){
		return (
      		<button onClick={this.handleClick}>Click me</button>
    	)
	}
}

在constructor里面有行代码是this.handleClick = this.handleClick.bind(this),为什么这么写呢,如果去掉,我们会发现,button点击的时候, handleClick里面的this是undefined的,而不是PersonForm这个类实例,这和直觉相违背( 特别是写过java的开发人员)。但上面这种写法又很烦人,如果有20个方法,我们就得写20个bind,那怎么解决这个问题呢?

两种解决办法

一种是使用class properties,即类属性

上面的可以改成下面写法,就简洁很多

class PersonForm extends React.Component{
	handleClick = ()=>{
		console.log(this)
	}
	render(){
		return (
      		<button onClick={this.handleClick}>Click me</button>
    	)
	}
}

这里面,我们就要详细了解下类属性,类属性有以下几种特性

  1. 类属性不在prototype上
  2. 类属性函数中的this固定绑定到类实例上

我们可以做如下实验

class PersonForm extends React.Component{
	handleClick = ()=>{
		return this;
	}
	render(){
		return (
      <button onClick={this.handleClick}>Click me</button>
    )
	}
}

let personForm = new PersonForm;

console.log(1, personForm.__proto__.handleClick) // undefined
console.log(2, personForm.handleClick.call(undefined)) // personForm实例
另一种是使用箭头函数调用
class PersonForm extends React.Component{
	handleClick(){
		console.log(this)
	}
	render(){
		<button onClick={()=> this.handleClick()}>
		</button>
	}
}

这种方法通常没什么问题,但有时会有性能影响,如果做为一个prop传递到子组件时,可能会导致子组件重新渲染。

给大家的思考: 为什么可能会重新渲染

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值