使用 Object.assign 和 React.Component

Using Object.assign with React.Component

我将这个示例代码放在一起,想看看 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')
);

您正在寻找的是旧版(ES6 之前的)语法:

const Example = React.createClass({
    render () {
      return (
        <h1>Does this work?</h1>
      );
    }
  });

可以在 documentation on using React without ES6 中找到更多信息。

你正在尝试做的事情根本不应该起作用。

您正在尝试使用不受支持的方式创建 React 组件。创建合适的 React 组件的三种方法是:

class MyComponent extends React.Component { //class implementation
}
let MyComponent = React.createClass({ // class implementation
});
function MyCompent (props, context) { // component render method
}

基本上可以归结为:

  • 声明扩展 React.Component 的 class(第一种形式)。
  • 从对象(第二种形式)创建 class return 某种 "constructor" 对象。
  • 正在实现渲染功能。

您将这些表单中的每一个都交给 React 来更新和渲染组件树。

你所做的是尝试(我猜)用 Object.assign 创建一个 React.Component 的实例,然后将它传递给 React 进行渲染。

React 不是这样工作的。相反,你给它一个 "constructor" (前两种形式)实现 #render() => reactElement (一种 return 反应元素而不是组件的方法)或者你传递给它一个函数也 returns React 元素。

PS : 要在不使用 new 的情况下创建 class 的 实例 ,Es5 引入了 Object.create:

var o = Object.create(proto); // o.__proto__ === proto
// the returned object has the supplied arguments as prototype.

下面的作品没有 createClassextends

const Example = (props, context) => Object.assign(
  {},
  Object.create(React.Component.prototype),
  {
    props, context,
    state: {text: 'acutally'},
    render () {
      return (
        <span>This {this.state.text} works</span>
      );
    }
  }
)