autobinder:Babel插件,用于在类构造函数中自动绑定您的componentclass方法

  • q5_402070
    了解作者
  • 5.8KB
    文件大小
  • zip
    文件格式
  • 0
    收藏次数
  • VIP专享
    资源类型
  • 0
    下载次数
  • 2022-06-15 07:41
    上传日期
babel-plugin-auto-binder 灵感: 每次编写新的组件方法时,都必须绑定到构造函数中,以便它可以访问this 。 示例: this.doStuff = this.doStuff.bind(this); 现在,如果您忘记绑定方法,您将面临非常奇怪的错误,这些错误可能会令人沮丧。 babel-plugin-auto-binder将通过在后台进行绑定来解决此问题,因此您只需要担心功能。 如果您正在使用或更喜欢使用箭头函数,则不需要此插件,因为箭头函数在声明它们的作用域中具有this上下文。 性能: 这个插件在构造函数中只绑定一次您的类方法(不绑定React中的react生命周期方法),这是一个很大的性能优势。 入门 配置 npm i -D babel-plugin-auto-binder npm i -D babel-plugin-transform-decorators-legacy 通过添加更新.babelrc配置 { "plugins" : [ "auto-binder", "transform-decorators-legacy"
autobinder-master.zip
  • autobinder-master
  • .babelrc
    37B
  • LICENSE
    1KB
  • README.md
    1.8KB
  • .gitignore
    13B
  • index.js
    221B
  • package-lock.json
    7.8KB
  • AutoBindClass.js
    2.1KB
  • package.json
    551B
内容介绍
# babel-plugin-auto-binder [![Maintainability](https://api.codeclimate.com/v1/badges/33a25ae1b4b593afa94f/maintainability)](https://codeclimate.com/github/HarshwardhanSingh/autobinder/maintainability) ## Inspiration: Every time I write a new component method I have to bind in the constructor so that it can access `this`. Example: `this.doStuff = this.doStuff.bind(this);` Now if you forget to bind your method, you will face very weird bugs which can be frustating. `babel-plugin-auto-binder` will take care of this issue by doing this binding behind the scene so you just worry about the functionality. If you are using or prefer using arrow functions then you don't need this plugin as the arrow function have the `this` context from the scope they are declared in. ## Performance: This plugin binds your class methods (does not binds react lifecycle methods in React) only once in constructor which is a big performance plus. ## Getting Started ### Setting up 1. `npm i -D babel-plugin-auto-binder` 2. `npm i -D babel-plugin-transform-decorators-legacy` 3. Update your `.babelrc` configuration by adding ``` { "plugins" : [ "auto-binder", "transform-decorators-legacy", ] } ``` ### Usage Decorate your class with `@autobind` decorator like this: ``` @autobind class App extends Component { constructor() { super(); } doStuff() { //some api calls } render() { return ( <div> <SomeComponent onSubmit={this.doStuff} /> </div> ) } } ``` and that's it!! The above input will get transformed to ``` class App extends Component { constructor() { super(); this.doStuff = this.doStuff.bind(this); } doStuff() { //some api calls } render() { return ( <div> <SomeComponent onSubmit={this.doStuff} /> </div> ) } } ```
评论
    相关推荐