如果与es6箭头函数一起使用,则React.createClass中'this'的词法范围 [英] Lexical scope of 'this' in React.createClass if used with es6 arrow functions
问题描述
我对es6还是比较陌生.我正在跟踪有关创建React组件的教程,并想知道es6箭头函数在定义组件函数时是否可以正常工作.考虑到使用箭头功能时'this'的词法范围,我认为它会起作用.
I am relatively new to es6 and react. I was following up a tutorial on creating react components and wondered if es6 arrow functions would work same while defining the component functions. Given the lexical scope of 'this' while using arrow functions, i thought it would work.
但是,在babel转译的代码中,此"对象似乎已解析为未定义".关于为什么它不能解析为定义组件变量的任何具体解释?尽管使用速记方法和扩展es6类是可行的,但我只是很好奇.
But 'this' object seems to be resolving to 'undefined' in babel transpiled code. Any specific explanation on why this does not resolve to the defining component variable ? Although using method shorthand and extending es6 classes works, i am just curious.
带有箭头功能的组件:
const PromptContainer = React.createClass({
getInitialState: () => ({
username: '',
}),
onInputChange: (e) => {
this.setState({
username: e.target.value,
});
},
render: () => (
<div className="jumbotron col-sm-6 col-sm-offset-3 text-center">
<h1>{this.props.header}</h1>
<div className="col-sm-12">
<form>
<div className="form-group">
<input
className="form-control"
type="text"
onChange={this.onInputChange}
placeholder="Github Username"
value={this.state.username}
/>
</div>
</form>
</div>
</div>
),
});
推荐答案
鉴于使用箭头功能时'this'的词法范围,我认为它会起作用.
Given the lexical scope of 'this' while using arrow functions, i thought it would work.
然后您会误解词汇范围的含义.它的作用与您想要的相反.
Then you are misunderstanding the meaning of lexical scope. It does the opposite of what you want.
var foo = () => this;
几乎完全像
var _temp = this;
var foo = () => _temp;
这意味着
const PromptContainer = React.createClass({
getInitialState: () => {
this;
},
onInputChange: (e) => {
this;
},
render: () => {
this;
},
});
是
var _temp = this;
const PromptContainer = React.createClass({
getInitialState: () => {
_temp;
},
onInputChange: (e) => {
_temp;
},
render: () => {
_temp;
},
});
因此您的任何函数都不会访问该函数的this
,它们会访问createClass
调用外部的this
,该调用是未定义的.
so none of your functions ever access this
of the function, they access the this
of that exists outside the createClass
call, which is `undefined.
如果您想以一种简短的方式编写所需的内容,请使用简洁的方法语法:
If you want a short way to write what you want, use concise method syntax:
const PromptContainer = React.createClass({
getInitialState() {
this;
},
onInputChange(e) {
this;
},
render() {
this;
},
});
这篇关于如果与es6箭头函数一起使用,则React.createClass中'this'的词法范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!