本篇文章记录如何在react-native中使用es7的decorator提案
了解decorator
或者看阮一峰的ECMAScript 6 入门
配置babel
#安装依赖
在react-native项目里安装 babel-plugin-transform-decorators-legacy 和 babel-preset-react-native 这两个库:
1 | npm install --save-dev babel-plugin-transform-decorators-legacy |
#.babelrc
在项目根目录(package.json所在的目录)添加 .babelrc 文件:
1 | { |
其中"presets": ["react-native"]是为了让babel首先兼容react-native的其他配置,参考babel-preset-react-native
应用
#autobind
举例使用 autobind-decorator 这个库, 其作用是在声明方法时自动bind(this):
安装
1 | npm install --save autobind-decorator |
为类方法添加装饰器
1 | import React from 'react'; |
#更多使用decorator的例子
- 为组件实现scu, 参考pure-render-decorator
- 打印生命周期方法的调用log
1 | @lifecycleLog |
推广
同理可得任意需要扩展babel plugin的配置方法