React 学习(九) HOC增强组件(函数)

Higher-Order Components (HOC)

HOC is a function with arguments as component and return value as new function

// index.js
ReactDOM.render(<App name="Smallstars" />, document.getElementById("root"));

// Components
import React, { PureComponent } from "react";

class App extends PureComponent {
  render() {
    return (
      <div>
        App:
        {this.props.name}
      </div>
    );
  }
}

const EnhanceComponent = (WrappedComponent) => {
  class NewComponent extends PureComponent {
    render() {
      return <WrappedComponent {...this.props} />;
    }
  }

  // Change the display name of Components
  NewComponent.dispalyName = "StarsComponents";
  return NewComponent;
};

const EnhanceComponent2 = (WrappedComponent) => {
  function NewComponent(props) {
    return <WrappedComponent {...props} />;
  }

  // Change the display name of Components
  return NewComponent;
};

export default EnhanceComponent(App);
posted @ 2020-12-02 17:00  北冥雪  阅读(101)  评论(0编辑  收藏  举报