简单的高阶组件

假设每次组件安装时我们都想要 console.log:

hocLogger.js

export default function hocLogger(Component) {
  return class extends React.Component {
    componentDidMount() {
      console.log('Hey, we are mounted!');
    }
    render() {
      return <Component {...this.props} />;
    }
  }
}

在代码中使用此 HOC:

MyLoggedComponent.js

import React from "react";
import {hocLogger} from "./hocLogger";

export class MyLoggedComponent extends React.Component {
    render() {
        return (
            <div>
                This component get's logged to console on each mount.
            </div>
        );
    }
}

// Now wrap MyLoggedComponent with the hocLogger function 
export default hocLogger(MyLoggedComponent);