我在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/