reactjs - React 仅将组件方法绑定(bind)到此 - 解决方法吗?

标签 reactjs

在使用 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)。

关于reactjs - React 仅将组件方法绑定(bind)到此 - 解决方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33582605/

相关文章:

reactjs - react-dnd:拖出一条线

javascript - 这个类可以改成React无状态函数吗?

css - 无法在与样式化组件的 react 中实现图像转换

javascript - react 路由器位置不匹配任何路线

javascript - Uncaught Invariant Violation : Too many re-renders. React 限制渲染次数以防止无限循环

javascript - React js中默认为数组的每个对象设置一个属性

reactjs - 无法读取未定义的属性 'subscribe'-Redux Persist

javascript - 如何在 React 中将 id 传递给 componentdidmount

unit-testing - 向 React 组件发送 props 以进行 Jest 单元测试

reactjs - 如何将 axios 中的数组参数传递到 Spring Controller ?