【问题标题】:Lexical scope of 'this' in React.createClass if used with es6 arrow functions [duplicate]如果与 es6 箭头函数一起使用,则 React.createClass 中“this”的词法范围 [重复]
【发布时间】:2016-05-12 18:21:15
【问题描述】:

我对 es6 相对较新,并且有反应。我正在跟进一个关于创建反应组件的教程,并想知道 es6 箭头函数在定义组件函数时是否可以正常工作。鉴于使用箭头函数时“this”的词法范围,我认为它会起作用。

但“this”对象似乎在 babel 转译代码中解析为“未定义”。关于为什么这不能解决定义组件变量的任何具体解释?虽然使用方法简写和扩展 es6 类是可行的,但我只是好奇。

带有箭头功能的组件:

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>
  ),
});

【问题讨论】:

    标签: javascript reactjs ecmascript-6 babeljs


    【解决方案1】:

    考虑到使用箭头函数时“this”的词法范围,我认为它会起作用。

    那你误解了词法作用域的意思。它与您想要的相反。

    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,即“未定义”。

    如果你想用一种简短的方式来写你想要的东西,请使用简洁的方法语法:

    const PromptContainer = React.createClass({
      getInitialState() {
        this;
      },
      onInputChange(e) {
        this;
      },
      render() {
        this;
      },
    });
    

    【讨论】:

    • 在 react class es6 格式中,下面的一个工作,是负责将“this”上下文绑定到类组件的转译器吗? class Button extends React.Component { // Use an arrow function here: handleClick = () =&gt; { console.log('clickity'); } render() { return ( // this binding works &lt;button onClick={this.handleClick}/&gt; ); } }
    • class Foo { prop = () =&gt; { /* stuff */}; } 语法是一种实验性建议语法,在这种情况下,该语法将 this 定义为类的实例,因此它具有与自动绑定类似的行为,但不是完全一样,因为自动绑定会导致函数的一个副本具有许多绑定函数,而这种语法会导致函数的多个副本。
    【解决方案2】:

    您应该将this 绑定到事件处理程序方法:

    onChange={this.onInputChange.bind(this)}
    

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 2018-07-02
      • 2016-09-07
      • 2015-03-17
      • 2016-01-08
      • 2020-08-30
      相关资源
      最近更新 更多