簡單的高階元件

假設每次元件安裝時我們都想要 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);