多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## React ES6的bind技巧 >React有两种创建组件的方式。 使用ES6 extends 来创建组件的话, 组件里面的方法,需要 ```javascript this.funName.bind(this) ``` 每次为方法添加 bind 方法,很麻烦。 推荐两个库,给ES6 带来自动绑定的方法 ## 一、使用装饰器 decorator [autobind-decorator](https://github.com/andreypopp/autobind-decorator) `npm install autobind-decorator` ```javascript import autobind from 'autobind-decorator' class Component { constructor(value) { this.value = value } @autobind method() { return this.value } } let component = new Component(42) let method = component.method // .bind(component) isn't needed! method() // returns 42 // Also usable on the class to bind all methods @autobind class Component { } ``` ## 二、使用方法的形式 [React-autobind](https://github.com/cassiozen/React-autobind) ```javascript import autoBind from 'react-autobind'; ... constructor(props) { super(props); autoBind(this); } ``` ## 结束语 了解具体的用法,请到 github 里面看 文档。