![](/img/trans.png)
[英]When using React Is it preferable to use fat arrow functions or bind functions in constructor?
[英]Bind in constructor or fat arrow in class
所以我想知道这是否有区别:
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>
);
}
}
我想知道每个功能的性能是否相同,还是有任何其他好处?
进一步阅读( https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f#.khf30fuaq )
绑定事件处理程序的最佳位置是constructor
。 这样,您的事件处理程序将其上下文绑定到组件实例。您可以访问props and state
并从此绑定处理程序中调用setState
或forceUpdate
。
与arrow
功能绑定也有其自身的优点。 箭头函数始终从定义它们的位置获取上下文。 所以实际上,这个例子相当于:
箭头函数语法是一种使用如下语法定义函数的方法:
change = (ev) => this.setState({ text: ev.target.value });
它比编写function(ev) { .... }
语句更简洁。 如果在=>
箭头后没有提供{
和}
括号,则此函数是一个立即返回的表达式。 所以这就像以下一样:
change = function(ev) { return this.setState({ text: ev.target.value }); }.bind(this);
因此.bind()
和arrow
函数都会导致创建一个新函数
总而言之,您希望绑定函数的方式取决于您的用例。
欲了解更多详细信息,你可以阅读了该文章:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.