我的印象是 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 风格的类不被实例化,并得到类似的结果。
最佳答案
Why is “normal” ES5 prototypal inheritance not supported in React?
是的,尽管使用 React.createClass
可能是您更好的选择。只是您问题中的代码没有执行标准的 ES5 类类继承任务。特别是:
- 您返回的是普通对象的实例,而不是
Board
的实例,因此该对象未使用Board.prototype
。通常,构造函数不应该返回任何东西,并且应该使用调用它时创建的对象new
,它接收为this
。 - 你没有给
React.Component
初始化实例的机会。 - 您没有在
Board.prototype
上设置constructor
(虽然我不知道 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>
关于javascript - React中如何实现 "normal"ES5原型(prototype)继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40366024/