2017-06-29 63 views
2

我有一个基本的React应用程序,我想将一些常用的功能放入基本组件类中,并让所有其他组件都从该类继承以获得对这些功能的访问。我有这样的:这个关键字在React基类中是未定义的

export class BaseComponent extends React.Component { 
    constructor() { 
     super(); 
     this.commonlyUsedMethod = this.commonlyUsedMethod.bind(this); 
    } 

    commonlyUsedMethod() { 
     let x = this.someValue; // <--- 'this' is undefined here 
    } 
} 

export class SomeComponent extends BaseComponent { 
    onButtonClick() { 
     super.commonlyUsedMethod(); 
    } 

    render() { 
     return whatever; 
    } 
} 

的问题是,当我打电话super.commonlyUsedMethod()从派生类,this.someValueBaseComponent.commonlyUsedMethod()炸毁因为thisundefined。我在BaseComponent构造函数中调用this.commonlyUsedMethod.bind(this);,所以我不确定发生了什么。

+1

你得到的实际错误信息是什么?调用'onButtonClick'的代码在哪里?你记得把'onButtonClick'绑定到'this'吗?为什么'onButtonClick'调用'super.commonlyUsedMethod'而不是'this.commonlyUsedMethod'? –

+0

我同意@JordanRunning。为什么'onButtonClick'正在调用'super.commonlyUserMethod'而不是'this.commonlyUserMethod' –

+1

@ whs.bsmith,所以你的组件不会扩展'React.Component'? – robertklep

回答

1

首先,我(和大多数React开发社区)不建议您使用继承。 https://facebook.github.io/react/docs/composition-vs-inheritance.html

大多数使用情况下,您可以使用Higher Order Components或在JS文件中编写函数并导入它来解决此问题。

如果你还想继续做下去。
您需要绑定this当您将buttonClick听众

export class SomeComponent extends BaseComponent { 
    onButtonClick() { 
     super.commonlyUsedMethod(); 
    } 

    render() { 
     return <div onClick={this.onButtonClick.bind(this)}>Hello</div>; 
    } 
} 

这里是它的工作示例。 https://www.webpackbin.com/bins/-Knp4X-n1RrHY1TIaBN-

更新:问题是不调用超级适当this,问题是与附加的的onClick侦听器时没有约束力适当this。感谢@Mayank指出。

+1

可以请你告诉我我在这里失踪,因为它没有'.call(this)'工作:https:/ /www.webpackbin.com/bins/-Knp7eAm845FhLPb_Mcf –

+0

你是对的。我现在意识到了。更新了答案 –

+0

这工作,谢谢你。调用'super.commonlyUsedMethod()'和'this.commonlyUsedMethod()'有区别吗?在标准的OO练习中,你可以使用'this'。如果你在下面看到我的答案,它似乎工作。 – d512

0

所以我不知道这是否一个好的做法™,但我可以得到它通过调用this.someCommonMethod()而不是super.someCommonMethod(),像这样的工作:

export class SomeComponent extends BaseComponent { 
    constructor() { 
     super(); 
     this.onButtonClick = this.onButtonClick.bind(this); 
    } 

    onButtonClick() { 
     this.commonlyUsedMethod(); <--- changed 'super' to 'this' 
    } 

    render() { 
     return whatever; 
    } 
} 

我足够新反应和ES6不知道这是如何工作的。任何想法将不胜感激。

+0

但是如果你在那里创建了相同的命名函数,你将不得不在继承类中做超类 –