React 最新版本支持ES6的写法,配合上Babel,写起来挺嗨的,总结一下ES6的一些写法:
React ES6+写法
1 | // 多加一层继承, 可以在baseComponent中做一些文章. |
官方的一个例子:
1 | export class Counter extends React.Component { |
React ES6 事件绑定
官方原话:
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!
新的ES6写法如果要实现this还指向当前对象,有三种写法:个人感觉箭头函数写法最优雅.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41第一种:this._handleClick.bind(this)
_handleClick(e) {
console.log(this);
}
render() {
return (
<div>
<h1 onClick={this._handleClick.bind(this)}>点击</h1>
</div>
);
}
第二种:this._handleClick = this._handleClick.bind(this)
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) => {}
_handleClick = (e) => {
// 使用箭头函数(arrow function)
console.log(this);
}
render() {
return (
<div>
<h1 onClick={this._handleClick}>点击</h1>
</div>
);
}
React ES6 写法,做封装一些待解决的问题
- 多层继承,props state等属性如何继承?
- 一些周期函数子类如何自动调用?而不是super.componentDidMount()这种显示调用