在使用React中 如果使用ES6的Class extends写法 如果onClick绑定一个方法 需要bind(this),
而使用React.createClass方法 就不需要.
请问这是为什么呢
在使用React中 如果使用ES6的Class extends写法 如果onClick绑定一个方法 需要bind(this),
而使用React.createClass方法 就不需要.
请问这是为什么呢
第一种
_handleClick(e) {
console.log(this);
}
render() {
return (
<div>
<h1 onClick={this._handleClick.bind(this)}>点击</h1>
</div>
);
}
第二种
constructor(props) {
super(props);
this._handleClick = this._handleClick.bind(this)
}
_handleClick(e) {
console.log(this);
}
render() {
return (
<div>
<h1 onClick={this._handleClick}>点击</h1>
</div>
);
}
第三种
_handleClick = (e) => {
// 使用箭头函数(arrow function)
console.log(this);
}
render() {
return (
<div>
<h1 onClick={this._handleClick}>点击</h1>
</div>
);
}
注释: 箭头函数需要在 编译的时候, 配置 支持 箭头函数参考文章
http://babeljs.io/blog/2015/06/07/react-on-es6-plus/
http://babeljs.io/blog/2015/10/31/setting-up-babel-6/
在props里使用 onClick={ this.handleClick.bind(this) }
或者 onClick={ (e) => this.handleClick(e) }
或者 onClick={ ::this.handleClick }
都会产生性能问题,所以现在eslint在语法检查时就会阻止这几种写法,问题原因是每一次render的时候如果遇到这些写法,都会重新用handleClick函数与this去绑定从而重新创建一个新的函数,影响性能。 如果使用下面的写法则不会每次都创建:
// 1.
constructor() {
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) { /* ... */ }
// 2.
handleClick = (e) => { /* ... */ };
确实有很多问题,react+ES6。楼上贴出来是一部分,另外官网也介绍了其他局限,比如initialState mixin propTypes defaultPros等都要注意。
所以我觉得要么就用creatClass省事
_handleClick() {
console.log(this);
}
render() {
return (
<div>
<h1 onClick={::this._handleClick}>点击</h1>
</div>
);
}
1 回答1.8k 阅读✓ 已解决
4 回答1.8k 阅读✓ 已解决
2 回答1.7k 阅读✓ 已解决
4 回答1.5k 阅读
4 回答1.1k 阅读
1 回答1.6k 阅读✓ 已解决
1 回答1.6k 阅读✓ 已解决
React自动绑定
Autobinding: When creating callbacks in JavaScript, you usually need to explicitly bind a method to its instance such that the value of this is correct. With React, every method is automatically bound to its component instance. React caches the bound method such that it's extremely CPU and memory efficient. It's also less typing!