• React 高阶组件(HOC)


    高阶组件(HOC)是 React 中用于复用组件逻辑的一种高级技巧。

    1. 简单用法

    import React, { Component } from "react";
    
    const withMouse = (AppComponent) => {
      class HOC extends Component {
        constructor(props) {
          super(props);
          this.state = { x: 0, y: 0 };
        }
    
        bindMouseMove = (event) => {
          this.setState({
            x: event.clientX,
            y: event.clientY,
          });
        };
    
        render() {
          return (
            <div
              style={{ border: "1px solid #eee", height: 400,  400 }}
              onMouseMove={this.bindMouseMove}
            >
              <h5>高阶组件</h5>
              <AppComponent {...this.props} mousePosition={this.state} />
            </div>
          );
        }
      }
      return HOC;
    };
    
    const App = (props) => {
      const { x, y } = props.mousePosition;
      return (
        <p>
          mousePosition position is ({x}, {y})
        </p>
      );
    };
    
    
    <!--高阶组件 withMouse -->
    export default withMouse(App);
    

    redux 中 connect

    import { connect } from "react-redux";
    
    const TodoList = connect(mapStateToProps, mapDispatchToProps)(TodoList);
    
    export default TodoList;
    

    connect也是一个高阶组件:

    export const connect = (mapStateToProps, mapDispatchToProps) => (
      WrappedComponent
    ) => {
      class Connect extends Component {
        constructor(props) {
          super(props);
          this.state = {
            allProps: {},
          };
        }
    
        /* 
        中间省略公共逻辑 
        mapStateToProps = (state) => {
            return { allProps: state.allProps };
        };
    
        mapDispatchToProps = (dispatch) => {
            return { ... };
        }; 
        */
        render() {
          return <WrappedComponent {...this.state.allProps} />;
        }
      }
      return Connect;
    };
    
    
  • 相关阅读:
    Python——thread
    Python——dummy_thread( _dummy_thread in Python 3.+)
    Python——pyiso8601
    Python——os(一)进程参数
    Python——eventlet.hubs
    Python——eventlet.backdoor
    Python——eventlet.greenthread
    解决zabbix可用性为灰色状态
    实时查看docker容器日志
    docker pull 报错Get https://xxx.xxx.xxx.xxx:5000/v1/_ping: http: server gave HTTP response
  • 原文地址:https://www.cnblogs.com/cckui/p/14596109.html
Copyright © 2020-2023  润新知