javascript - 使用在 ES6 React Component 类之外声明的方法

标签 javascript oop reactjs

我在reactjs ES 6中有下面的代码,但它不起作用。我的问题是:如何使用组件类之外的方法?单个文件中是否可以包含许多组件类?多谢。

function methodOutside(){
   /** Do something else **/  
}

class myComponent1 extends React.Component{
  constructor(){
    super();
    this.methodInside1 = this.methodInside1.bind(this);
  }

  methodInside(){

   /**Do something **/
  }

  render(){
     this.methodInside1();
     methodOutside();
  }

}

class myComponent2 extends React.Component{
  constructor(){
    super();
    this.methodInside2 = this.methodInside2.bind(this);
  }

  methodInside(){

   /**Do something **/
  }

  render(){
     this.methodInside2();
     methodOutside();
  }

}

最佳答案

我在评论中发布的答案。将其发布在这里,以便其他人更容易看到它。

this.methodInside2 = this.methodInside2.bind(this);this.methodInside1 = this.methodInside1.bind(this); 您似乎正在调用 bind在一些未定义的事情上。你不是说 this.methodInside1 = this.methodInside.bind(this);

尽管我看不出这样做的意义,因为您只需从 render() 方法调用 this.methodInside() 即可。 this 将按照您的预期进行绑定(bind)。

关于javascript - 使用在 ES6 React Component 类之外声明的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32086653/

相关文章:

python - 如何将类 __init__ 参数限制为另一个类的列表?

javascript - 如何在React中实现GET方法getById?

javascript - 为什么我的底部子组件显示在页面顶部?

javascript - 如何在express js中将url参数传递给模板

javascript - $http GET 刷新页面

javascript - 使用jquery时如何获取HTML5 Canvas ?

c++ - 如何在运行时确定消息类型?

oop - 使用大量的多态性是不是很糟糕?

javascript - react /归还传奇 : Need to trigger a route change after user clicks button on form

javascript - 基于动态生成的文本和特定图案的颜色 li 元素