admin管理员组文章数量:1405314
I am currently working on a react app, and I found having to bind this
a bit cumbersome when a ponent class has many functions.
Example
class Foo extends Component {
constructor(props){
super(props);
this.function1 = this.function1.bind(this);
this.function2 = this.function2.bind(this);
this.function3 = this.function3.bind(this);
}
function1() {
...
}
function2() {
...
}
function3() {
...
}
}
Is there a more efficient way to do this?
I am currently working on a react app, and I found having to bind this
a bit cumbersome when a ponent class has many functions.
Example
class Foo extends Component {
constructor(props){
super(props);
this.function1 = this.function1.bind(this);
this.function2 = this.function2.bind(this);
this.function3 = this.function3.bind(this);
}
function1() {
...
}
function2() {
...
}
function3() {
...
}
}
Is there a more efficient way to do this?
Share Improve this question edited Jun 4, 2020 at 2:33 Yilmaz 50k18 gold badges218 silver badges271 bronze badges asked Jan 12, 2017 at 16:46 Faraz KhanFaraz Khan 1033 bronze badges 2- how are the functions being used? – Daniel A. White Commented Jan 12, 2017 at 16:48
- You can also bind it in-line as mentioned in this or this post – RBT Commented Apr 30, 2017 at 6:48
2 Answers
Reset to default 10You can avoid having to bind methods by using the transform-class-properties Babel plugin, which is an experimental ES7 feature. Make sure you enable stage-0 in order to use it.
This allows the use of arrow functions when defining your class methods, leveraging arrow functions' lexical binding so this
refers to function's context (in this case the class), like so:
class Foo extends Component {
boundFunction = () => { /* 'this' points to Foo */ }
}
You can shorten it a bit with:
this.function1 = ::this.function1
You'll need https://babeljs.io/docs/plugins/transform-function-bind/
本文标签: javascriptIs there a better way to bind 39this39 in React Component classesStack Overflow
版权声明:本文标题:javascript - Is there a better way to bind 'this' in React Component classes? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744334683a2601131.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论