【问题标题】:Using Object.assign with React.Component将 Object.assign 与 React.Component 一起使用
【发布时间】: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


【解决方案1】:

您正在尝试做的事情根本不应该工作。

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

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

基本上归结为:

  • 声明一个扩展React.Component的类(第一种形式)。
  • 从一个对象创建一个类(第二种形式)都返回某种“构造函数”对象。
  • 实现渲染功能。

您将这些表单中的每一个都提供给 React 以更新和呈现组件树。

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

React 不能以这种方式工作。相反,您可以给它一个“构造函数”(前两种形式),它实现了 #render() => reactElement(一个返回 React 元素而不是组件的方法),或者你传递一个也返回 React 元素的函数。

PS : 为了在不使用 new 的情况下创建一个类的 instance,Es5 引入了 Object.create:

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

【讨论】:

    【解决方案2】:

    您正在寻找的是遗留(ES6 之前)语法:

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

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

    【讨论】:

      【解决方案3】:

      下面的工作没有createClass 或extends

      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>
            );
          }
        }
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-07
        • 2015-08-20
        • 2017-05-11
        • 2019-08-22
        • 2018-05-29
        • 1970-01-01
        • 2016-07-18
        • 2021-10-01
        相关资源
        最近更新 更多