如何实施" normal" React中的ES5原型继承?

时间:2016-11-01 18:10:56

标签: javascript reactjs prototypal-inheritance es6-class

我的印象是,ES6类基本上是围绕ES5对象系统的语法糖。 当我试图在没有转换器的情况下运行React时,我认为我可以使用旧语法来定义对象"类" "继承"来自React.Component。

    var Board = function(props, state) {
        var instance = {};

        instance.props = props;
        instance.context = state;

        return(instance);           
    };

    Board.prototype = Object.create(React.Component.prototype);

    Board.prototype.render = function() {
        return(
            // ...stuff
        )               
    };

但这不起作用!

react.js:20478 Warning: Board(...): No `render` method found on the returned component instance: you may have forgotten to define `render`
react.js:6690 Uncaught TypeError: inst.render is not a function(…)

我找到了替代in this gist,以下作品:

    var Board = function(props, state) {
        var instance = Object.create(React.Component.prototype);

        instance.props = props;
        instance.context = state;

        instance.prototype.render = function() {
            return(
                // ...stuff
            )               
        };

        return(instance);           
    };

我还发现我可以使用React.createClass帮助器。

但我仍然想理解为什么React不会处理以这种常见方式定义的类。在我看来,ES6类在使用之前就已经实现了。我认为没有理由为什么ES5风格的类也不会被实例化,结果相似。

1 个答案:

答案 0 :(得分:6)

  

为什么React不支持“正常”的ES5原型继承?

虽然使用React.createClass可能是您更好的选择。只是问题中的代码没有执行标准的ES5类继承任务。特别是:

  • 您正在返回普通对象的实例,而不是Board的实例,因此对象不使用Board.prototype。通常,构造函数不应该返回任何内容,并且应该使用在调用它时创建的对象new,它接收为this
  • 您没有给React.Component初始化实例的机会。
  • 你没有在constructor上设置Board.prototype(虽然我不知道React是否关心;很多事情都没有。)

如果您以正常方式进行设置,它会起作用。这是没有React.createClass的ES5示例,请参阅注释:

// The component
function Foo(props) {
    // Note the chained superclass call
    React.Component.call(this, props);
}

// Set up the prototype
Foo.prototype = Object.create(React.Component.prototype);
Foo.prototype.constructor = Foo; // Note

// Add a render method
Foo.prototype.render = function() {
    return React.createElement("div", null, this.props.text);
};

// Use it
ReactDOM.render(
    React.createElement(Foo, {
        text: "Hi there, the date/time is " + new Date()
    }),
    document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>