[英]Use a method declared outside of ES6 React Component class
我在下面的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);
您似乎正在对未定义的内容调用绑定。 您的意思不是this.methodInside1 = this.methodInside.bind(this);
尽管我看不到这样做的意义,但因为您可以从render()
方法调用this.methodInside()
。 正如您所期望的那样, this
将受到约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.