普通 es6 类和扩展 React.Component 有什么区别

2024-01-05

我在用着反应全栈 https://github.com/kriasoft/react-starter-kit作为开始我的项目的脚手架。

我发现它的示例代码与官方的 React 文档有很大不同。

示例代码是这样的:

@withStyles(styles)
class Header {

  render() {
    return (
     /* simple JSX code */
    );
  }
}


function withStyles(styles) {
  return (ComposedComponent) => class WithStyles {

    static contextTypes = {
      onInsertCss: PropTypes.func
    };

    constructor() {
      this.refCount = 0;
      ComposedComponent.prototype.renderCss = function (css) {
        let style;
        if (ExecutionEnvironment.canUseDOM) {
          if (this.styleId && (style = document.getElementById(this.styleId))) {
            if ('textContent' in style) {
              style.textContent = css;
            } else {
              style.styleSheet.cssText = css;
            }
          } else {
            this.styleId = `dynamic-css-${count++}`;
            style = document.createElement('style');
            style.setAttribute('id', this.styleId);
            style.setAttribute('type', 'text/css');

            if ('textContent' in style) {
              style.textContent = css;
            } else {
              style.styleSheet.cssText = css;
            }

            document.getElementsByTagName('head')[0].appendChild(style);
            this.refCount++;
          }
        } else {
          this.context.onInsertCss(css);
        }
      }.bind(this);
    }

    componentWillMount() {
       /* some implement */
    }

    componentWillUnmount() {
      /* some implement */
    }

    render() {
      return <ComposedComponent {...this.props} />;
    }

  };
}

它甚至没有延伸React.Component根本,我也看不到它使用原型继承。

但它确实有效,并且每个组件都可以像官方文档所说的那样使用。

这是否意味着如果我用以下方法实现一个类render方法,我实现一个React组件?


这是否意味着如果我用以下方法实现一个类render方法,我实现一个React组件?

Pretty much. React.Component https://github.com/facebook/react/blob/master/src/isomorphic/modern/class/ReactComponent.js only provides the methods setState and forceUpdate. You only have to inherit from React.Component if you need them. Edit: With the introduction of stateless components (functions), extending React.Component is actually required so that React can distinguish functions from class constructors.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

普通 es6 类和扩展 React.Component 有什么区别 的相关文章

随机推荐