What are the differences between plain es6 class a

2019-06-28 01:05发布

问题:

I'm using react-fullstack as scaffold to start my project.

I find its sample code is very different vs the official react document.

The sample code is like this:

@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} />;
    }

  };
}

It doesn't even extend React.Component at all, I can't see it use prototype inheritance either.

But it works, and every component can be used as official document said.

Does that mean if I implement a class with the render method, I implement a React component?

回答1:

Does that mean if I implement a class with the render method, I implement a React component?

Pretty much. React.Component 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.