问题描述
所以我想知道这是否有区别:
So i'm wondering if there is a difference between this:
import React, { Component, PropTypes } from 'react';
class Example extends Component {
constructor(props) {
super(props);
this.state = {
page : 1
};
}
nextPage = () => {
this.setState({ page: this.state.page + 1 });
}
previousPage= () => {
this.setState({ page: this.state.page - 1 });
}
render() {
const { page } = this.state;
return (
<div>
<H1>{page}</H1>
<Button onClickPrevious={this.previousPage} onClickNext={this.nextPage} />}
</div>
);
}
}
或
import React, { Component, PropTypes } from 'react';
class Example extends Component {
constructor(props) {
super(props);
this.nextPage = this.nextPage.bind(this);
this.previousPage = this.previousPage.bind(this);
this.state = {
page: 1
};
}
nextPage() {
this.setState({ page: this.state.page + 1 }); }
previousPage() {
this.setState({ page: this.state.page - 1 }); }
render() {
const { page } = this.state;
return (
<div>
<H1>{page}</H1>
<Button onClickPrevious={this.previousPage} onClickNext={this.nextPage} />}
</div>
);
}
}
我想知道它的性能是否相同每项功能还是有其他好处?
I'm wondering if it's the same in performance this to every function or are there any other benefits?
进一步阅读()
推荐答案
绑定事件处理程序的最佳位置是构造函数
。这样,您的事件处理程序将其上下文绑定到组件实例。您可以访问 props和state
并调用 setState
或来自此绑定处理程序的 forceUpdate
。
The best place to bind your event handlers is your constructor
. This way your event handler has its context bound to the component instance.You can access props and state
and call setState
or forceUpdate
from such bound handler.
使用箭头绑定
功能也有自己的优点。
箭头函数总是从定义它们的位置获取上下文。所以实际上,这个例子相当于:
Binding with arrow
functions have their own advantages as well.Arrow functions always gets the context from where they have been defined. So in fact, this example is equivalent to:
箭头函数语法是一种使用如下语法定义函数的方法:
The arrow function syntax is a way of defining function with a syntax like this:
change = (ev) => this.setState({ text: ev.target.value });
这比编写函数(ev){更简洁。 ...}
声明。如果您在 => $之后未提供
{
和}
括号c $ c> arrow,这样的函数是一个立即返回的表达式。因此,这类似于以下内容:
It is a more concise way than writing a function(ev) { .... }
statement. If you don’t provide {
and }
brackets after the =>
arrow, such function is a single expression which is returned instantly. So this desugars to something like:
change = function(ev) { return this.setState({ text: ev.target.value }); }.bind(this);
因此 .bind()
和箭头
函数导致创建一个新函数
And hence both of .bind()
and arrow
function cause a new function to be created
结束,你想绑定你的函数的方式取决于你的用例。
Concluding, the way you want to bind your function depends on your use case.
有关详细信息,请阅读 文章:
For more details you can read up this article:
这篇关于在课堂上绑定构造函数或胖箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!