【发布时间】:2017-01-23 15:31:06
【问题描述】:
我把这个示例代码放在一起,想看看为什么 React 会抛出错误。我试图将其解释为使用 React.Component 的后代的替代方法时遇到了困难。
const App = ({children}) => (
<div className="app">
{ children }
</div>
);
const Example = Object.assign(
{},
React.Component,
{
render () {
return (
<h1>Does this work?</h1>
);
}
}
);
ReactDOM.render(
<App>
<Example />
</App>,
document.querySelector('#target')
);
【问题讨论】:
-
真正的问题是为什么你甚至期望它能够工作。
React.Component是一个构造函数。如果你想扩展反应组件使用class Example extend React.Component. -
重点是远离
createClass,使用Component的类扩展,真正使用组合而不是继承。通过扩展React.Component构造函数,您正在创建伪类的后代,这似乎是不可避免的。我曾希望得到一个解释,除了框架不支持该功能。
标签: reactjs inheritance composition