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

到目前为止,我不必担心我的函数会绑定(bind)到我创建的 Component,但现在不再是这样了(为什么?!?),并且 Component 仅绑定(bind)到Component 父类(super class)(如果我正确理解了错误)。

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

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> 
  } 
} 

因此,如果我不绑定(bind) newFunction ,它将失败(没有 Prop 、状态或任何东西)。

有办法解决这个问题吗?

请您参考如下方法:

来自React documentation :

No Autobinding

Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.

所以,不存在绑定(bind) 0.14 中新增的所有方法的自动方法。但是,正如文档所示,您可以:

1)使用箭头函数(但是,如果您使用 Babel,则需要阶段 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) 您可以就地绑定(bind):

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)您可以就地使用箭头函数(类似于绑定(bind)):

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 点很好,但是您必须记住每个方法定义的语法。如果我有很多方法,我确实倾向于在构造函数中绑定(bind)。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!