Skip to content

React 高阶组件(高级)

关于组件公共逻辑的抽离

  • mixin,已被 React 弃用
  • 高级组件 Higher Order Component(简称 HOC)
  • Render Props

高阶组件基本用法

js
// 高阶组件不是一种功能,而是一种模式
const HOCFactory = (Component) => {
  class HOC extends React.Component {
    // 在此定义多个组件和公共逻辑
    render() {
      return <Component {...this.props} />; // 返回拼装的结果
    }
  }

  return HOC;
};

const EnhancedComponent1 = HOCFactory(WrappedComponent1);
const EnhancedComponent2 = HOCFactory(WrappedComponent2);

高阶组件实例

定义一个 HOCDemo.js

js
import React from 'react';

// 高阶组件
const withMouse = (Component) => {
  class withMouseComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        x: 0,
        y: 0,
      };
    }

    handleMouseMove = (e) => {
      this.setState({
        x: e.clientX,
        y: e.clientY,
      });
    };

    render() {
      return (
        <div style={{ height: '500px' }} onMouseMove={this.handleMouseMove}>
          {/*1、透传所有 props 2、增加 mouse 属性*/}
          <Component {...this.props} mouse={this.state} />
        </div>
      );
    }
  }

  return withMouseComponent;
};

const App = (props) => {
  const a = props.a;
  const { x, y } = props.mouse; // 接收 mouse 属性
  return (
    <div style={{ height: '500px' }}>
      <h1>
        The Mouse position is ({x},{y})
      </h1>
      <p>a:{a}</p>
    </div>
  );
};

export default withMouse(App);

测试下

js
<HOCDemo a="123" />

redux connect 是高阶组件

比如

js
import { connect } from 'react-redux';
const VisibleTodoList = connect(mapStateToProps, mapDispatchToProps)(TodoList);

export default VisibleTodoList;

基于 MIT 许可发布