所以我想知道这之间是否有区别:
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>
);
}
}
Or
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
or forceUpdate
来自这样的绑定处理程序。
结合与arrow
功能也有自己的优点。
箭头函数总是从定义它们的地方获取上下文。所以实际上这个例子就相当于:
箭头函数语法是一种定义函数的方法,语法如下:
change = (ev) => this.setState({ text: ev.target.value });
这是一种比编写更简洁的方法function(ev) { .... }
陈述。如果您不提供{
and }
后面的括号=>
箭头,此类函数是立即返回的单个表达式。所以这脱糖成这样:
change = function(ev) { return this.setState({ text: ev.target.value }); }.bind(this);
因此两者.bind()
and arrow
function 导致创建一个新函数
总之,您想要绑定函数的方式取决于您的用例。
欲了解更多详细信息,您可以阅读this文章:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)