我在下面的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);
尽管我看不到这样做的意义,但是因为您可以this.methodInside()
从render()
方法中进行调用。this
将按照您的期望进行绑定。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句