在react-native中使用es7的decorator

本篇文章记录如何在react-native中使用es7的decorator提案
了解decorator
或者看阮一峰的ECMAScript 6 入门

配置babel

#安装依赖

在react-native项目里安装 babel-plugin-transform-decorators-legacybabel-preset-react-native 这两个库:

1
2
npm install --save-dev babel-plugin-transform-decorators-legacy
npm install --save-dev babel-preset-react-native

#.babelrc

在项目根目录(package.json所在的目录)添加 .babelrc 文件:

1
2
3
4
5
6
7
8
{
"presets": [
"react-native"
],
"plugins": [
"transform-decorators-legacy"
]
}

其中"presets": ["react-native"]是为了让babel首先兼容react-native的其他配置,参考babel-preset-react-native

应用

#autobind

举例使用 autobind-decorator 这个库, 其作用是在声明方法时自动bind(this):
安装

1
npm install --save autobind-decorator

为类方法添加装饰器

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
import React from 'react';
import ReactNative from 'react-native';
const {
TouchableNativeFeedback,
View,
Text,
} = ReactNative;

import autobind from 'autobind-decorator';

class A extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
}

@autobind
handlePress() {
//此方法会被自动bind(this)
this.setState({
count: this.state.count + 1,
});
}

render() {
return (
<View style={{flex: 1}}>
<TouchableNativeFeedback onPress={this.handlePress}>
<View>
<Text>{this.state.count}</Text>
</View>
</TouchableNativeFeedback>
</View>
);
}
}

#更多使用decorator的例子

1
2
3
@lifecycleLog
class B extends React.Component {
}

推广

同理可得任意需要扩展babel plugin的配置方法