zoukankan      html  css  js  c++  java
  • 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;
    };
    
    
  • 相关阅读:
    VOIP开源项目源码地址(一)
    iptables下udp穿越实用篇
    function socket about http://net.pku.edu.cn/~yhf/linux_c/function/14.html
    IOKE的SIP协议专栏
    XviD core API overview: Decoding
    Socket about
    sql海量数据优化
    Socket、多线程、消息队列、共享资源并发下的性能研究
    【转】SQL 索引理解
    SQL 索引理解
  • 原文地址:https://www.cnblogs.com/cckui/p/14596109.html
Copyright © 2011-2022 走看看