Owe*_*wen 6 ecmascript-6 reactjs
我知道讨论范围问题的类似线程.
使用以下组件
import React from 'react';
import ReactDOM from 'react-dom';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
addMore() {
this.setState({
counter: this.state.counter + 1
});
}
render() {
return (
<div onClick={ this.addMore }>
<p>counter: { this.state.counter }</p>
</div>
);
}
}
if (document.getElementById('example')) {
ReactDOM.render(<Example />, document.getElementById('example'));
}
Run Code Online (Sandbox Code Playgroud)
当你点击div你得到Cannot read property 'setState' of null
我知道你可以做的事情,this.addMore.bind(this)但所有这些似乎是奇怪的额外样板代码风格代码只是为了使它工作.
什么被认为是最优雅的方式?当然,除了眼睛疼痛外,人们必须有一种优先的方式才能获得益处吗?
Moe*_*Moe 21
addMore = () => {
this.setState({
counter: this.state.counter + 1
});
}
Run Code Online (Sandbox Code Playgroud)
箭头语法this为您处理绑定
查看这个很棒的链接以获取更多信息,它显示了许多方法来实现这一点 http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html
您需要将正确的this上下文绑定到函数,并且可以通过添加this.addMore = this.addMore.bind(this);到构造函数来实现.
constructor(props) {
super(props);
this.state = {
counter: 0
}
this.addMore = this.addMore.bind(this);
}
Run Code Online (Sandbox Code Playgroud)
在ES5 React.createClass中,所有函数都自动绑定到正确的this但在ES6类中,正确的this上下文不会自动绑定.参考
这在构造函数中称为Bind,这是React文档中目前建议的"在应用程序中提高性能"的方法.参考
| 归档时间: |
|
| 查看次数: |
27126 次 |
| 最近记录: |