How To Implement "normal" Es5 Prototypal Inheritance In React?
I am under the impression that ES6 classes are basically a syntactic sugar around the ES5 objects system. As I am trying to run React without a transpiler, I figured that I could u
Solution 1:
Why is “normal” ES5 prototypal inheritance not supported in React?
It is, although using React.createClass
is probably your better option. It's just that the code in your question isn't doing the standard ES5 class-like inheritance tasks. In particular:
- You're returning an instance of a plain object, not an instance of
Board
, and soBoard.prototype
isn't used by the object. Normally, a constructor function shouldn't return anything, and should use the objectnew
created when calling it, which it receives asthis
. - You're not giving
React.Component
its chance to initialize the instance. - You're not setting
constructor
onBoard.prototype
(although I don't know whether React cares; a lot of things don't).
It works if you set it up in the normal way. Here's an ES5 example without React.createClass
, see comments:
// The componentfunctionFoo(props) {
// Note the chained superclass callReact.Component.call(this, props);
}
// Set up the prototypeFoo.prototype = Object.create(React.Component.prototype);
Foo.prototype.constructor = Foo; // Note// Add a render methodFoo.prototype.render = function() {
returnReact.createElement("div", null, this.props.text);
};
// Use itReactDOM.render(
React.createElement(Foo, {
text: "Hi there, the date/time is " + newDate()
}),
document.getElementById("react")
);
<divid="react"></div><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Post a Comment for "How To Implement "normal" Es5 Prototypal Inheritance In React?"