reactjs用剪头函数绑定this,告别constructor绑定this

 在写react组件的时候,你是不是也被constructor方法里的绑定this烦恼过(如下),如果不是,那就没必要看下去了...

	constructor(props){
		super(props);
		this.showAddQuestion=this.showAddQuestion.bind(this);
		this.hideAddQuestion=this.hideAddQuestion.bind(this);
		this.submitQuestion=this.submitQuestion.bind(this);		
		this.titleChange=this.titleChange.bind(this);
		this.substanceChange=this.substanceChange.bind(this);



	  	this.state = {
	  	  value:Map({
	  	  		title: "",//标题
		      	substance:"",//内容
		      	hideQuestion:true//隐藏提示框
	  	  })	
	    };		
	}

然后你想要用剪头函数的特性去绑定当前对象this的时候却报错了!怎么回事

其实完全可以用剪头函数来将绑定this,不过这有两个前提,首先就是你是使用bable来写的代码,然后就是我下面要说的了。

1.安装Class properties transform
babel --plugins transform-class-properties script.js
2.配置.babelrc
{
  "plugins": ["transform-class-properties"]
}

我的完整 .baelrc是下面这样的
//.babelrc
{
  "presets": [
    "react",
    "stage-0",
    "es2015"
  ], 
  "plugins": [
  	"transform-class-properties"
  ]
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值