JavaScript 中的原型继承到底是如何工作的?

Bog*_*gin 5 javascript inheritance reactjs

I\xe2\x80\x99m 仍然没有完全理解 JavaScript 中的继承二分法(原型与经典)。

\n\n

如果它class只是原型上的语法糖,我应该如何对其进行脱糖?

\n\n

class您可以向我展示使用类和原型(即没有& )创建 React 元素的不同方法吗React.createClass

\n\n

那么,有没有办法使用 Native 来获取有状态组件Object.create

\n\n

像这样:

\n\n
const Hello = Object.create(React.Component.prototype, {\n  componentDidMount: {\n    value: function() {\n      alert(\'Mounted\');\n    }\n  },\n  render: {\n    value: function() {\n      return <div>I love StackOverflow community! It is so helpful and friendly</div>;\n    }\n  }\n});\n\nReactDOM.render(<Hello />, document.getElementById(\'root\'));\n
Run Code Online (Sandbox Code Playgroud)\n\n

由于内部 lib\xe2\x80\x99s 的限制,似乎这样的东西不会 \xe2\x80\x99 工作。但为什么我们不能\xe2\x80\x99 更自然地使用 JavaScript 的原型性质呢?

\n\n

有\xe2\x80\x99s来自官方文档的注释: https: //facebook.github.io/react/docs/composition-vs-inheritance.html#so-what-about-inheritance

\n\n
\n

[...]我们还没有发现任何我们建议创建组件继承层次结构的用例

\n
\n\n

但\xe2\x80\x99class主要是关于继承吗?

\n\n

我\xe2\x80\x99m很困惑,想听听你对我的做法和想法错误的看法?

\n\n

我\xe2\x80\x99在Reactiflux上问过这个问题,Brendan Hurley提出了这个:https ://codepen.io/niechea/pen/xdVEvv?editors=0010

\n\n
function MyComponent(props) {\n  this.props = props;\n  this.state = {\n    clickCount: 0,\n  };\n}\n\nMyComponent.prototype = Object.create(React.Component.prototype);\n\nMyComponent.prototype.clickHandler = function() {\n  this.setState({\n    clickCount: this.state.clickCount + 1,\n  });\n}\n\nMyComponent.prototype.render = function() {\n  return (\n    <div>\n      <p>Hello, {this.props.name}.</p>\n      <p>You have clicked {this.state.clickCount} time(s)!</p>\n      <button onClick={this.clickHandler.bind(this)}>Click me</button>\n    </div>\n  );\n}\n\nReactDOM.render(<MyComponent name="Bogdan" />, document.getElementById(\'app\'));\n
Run Code Online (Sandbox Code Playgroud)\n\n

他的解决方案真的是原型吗?

\n\n
\n\n

以下是一些参考:

\n\n\n\n
\n\n

* 问题主要是关于继承,而不是关于React。这里的React只是一个参考。

\n

Cen*_*aya 0

抱歉我无法写任何评论。我认为你必须初始化下面的超类构造函数。

function MyComponent(props) {
  React.Component.prototype.apply(this, props);
  this.props = props;
  this.state = {
    clickCount: 0,
  };
}
Run Code Online (Sandbox Code Playgroud)