【问题标题】:React only binds Component methods to this - work around?React 仅将 Component 方法绑定到此 - 解决方法?
【发布时间】:2016-02-08 12:48:13
【问题描述】:

在使用 ES6 和 react 0.14 时,有没有办法避免样板?

到目前为止,我不必担心我的函数会绑定到我创建的Component,但这不再是(为什么?!?)这种情况,组件只绑定到Component super类(如果我正确理解了错误)。

所以我每次创建新类时真正需要做的就是将这段代码添加到构造函数中:

class CustomComp extends React.Component {

  constructor() {
    super();
    this.newFunction = this.newFunction.bind(this);
  }

  newFunction(){
    console.log('This is user defined function');

}
  render() {
    return <button onClick={this.newFunction}>Click</button>
  }
}

所以如果我不绑定newFunction,它将失败(没有道具、状态或任何东西)。

有没有办法解决这个问题?

【问题讨论】:

标签: reactjs


【解决方案1】:

来自React documentation

无自动绑定

方法遵循与常规 ES6 类相同的语义,这意味着 他们不会自动将此绑定到实例。你必须 明确使用 .bind(this) 或箭头函数 =>.

所以,没有一种自动方法可以绑定 0.14 中的所有新方法。但是,正如文档所建议的,您可以:

1) 使用箭头函数(但是,如果你使用 Babel,则需要 stage 0)

class CustomComp extends React.Component {

  constructor() {
    super();
  }

  newFunction = () => {
    console.log('This is user defined function');

}
  render() {
    return <button onClick={this.newFunction}>Click</button>
  }
}

2) 你可以就地绑定

class CustomComp extends React.Component {

  constructor() {
    super();
  }

  newFunction() {
    console.log('This is user defined function');

}
  render() {
    return <button onClick={this.newFunction.bind(this)}>Click</button>
  }
}

3)您可以在中使用箭头函数(类似于绑定):

class CustomComp extends React.Component {

  constructor() {
    super();
  }

  newFunction() {
    console.log('This is user defined function');

}
  render() {
    return <button onClick={() => this.newFunction()}>Click</button>
  }
}

如果我只有 1-2 种方法,我倾向于使用数字 2 和 3。数字 1 很好,但您必须记住每个方法定义的语法。如果我有很多方法,我倾向于在构造函数中绑定。

【讨论】:

  • 很好的答案。只是一点提示:你跳过{} 的额外集合,直接写onClick={() =&gt; this.newFunction()}
  • 很好的答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 2020-03-18
  • 2018-08-10
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 2013-05-04
相关资源
最近更新 更多