在写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"
]
}