Note: This post has been posted at the time React was NOT supporting ES6 (v12).
I have an ES6 class :
class BaseClass {
getInitialState(){
return {message: 'Hello!'};
}
render() {
return (
<div>
<div>{this.state.message}</div>
</div>
)
}
}
That I can export in ES6 using this expression (source : react ES6 browserify)
export default React.createClass(BaseClass.prototype)
This works fine. Now I would like to use ES6 inheritance to extend my BaseClass
class :
class ExtendedClass extends BaseClass{
getInitialState(){
return {message: "Hello! I'm an extension"};
}
}
But when I call React.createClass
on the ExtendedClass
class, I got the following exception :
Invariant Violation: ReactCompositeComponentInterface: You are attempting to define `constructor` on your component more than once. This conflict may be due to a mixin.
I know React 0.13 is supposed to be more ES6 friendly but is there any ways to handle that ?
EDIT:
I'm using Traceur to compile my ES6 classes. The output for ExtendedClass
looks like :
function ExtendedClass() {
"use strict";
if (BaseClass !== null) {
BaseClass.apply(this, arguments);
}
}
for (BaseClass____Key in BaseClass) {
if (BaseClass.hasOwnProperty(BaseClass____Key)) {
ExtendedClass[BaseClass____Key] = BaseClass[BaseClass____Key];
}
}
____SuperProtoOfBaseClass = BaseClass === null ? null : BaseClass.prototype;
ExtendedClass.prototype = Object.create(____SuperProtoOfBaseClass);
ExtendedClass.prototype.constructor = ExtendedClass;
ExtendedClass.__superConstructor__ = BaseClass;
ExtendedClass.prototype.getInitialState = function() {
"use strict";
return {message: "Hello! I'm an extension"};
};
React.createClass(ExtendedClass.prototype);
Here is the workaround I've found :
Inside
React.js
library, I've updated theReactCompositeComponentInterface
to add a custom policy forconstructor
(As far as I know there's no way to customize this 'interface' properly) :Then in the
ExtendedClass
, you have to redefine every method even if you don't customize them :I'm not happy with this dirty solution but it will do the job waiting for a 0.13 version that hopefully will solve those issues.