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;
    };
    
    
  • 相关阅读:
    javascript keycode大全
    在WEB环境下打印报表的crystal的解决方案
    Trim()
    C#应用结构体变量
    锚点定位
    C# 按地址传值
    [GIIS]JS 图片 Preview
    c# 模拟网站登陆
    此数据库没有有效所有者,因此无法安装数据库关系图支持对象" 解决方法
    风讯.NET与NETCMS的选择—开源.NET内容管理系统
  • 原文地址:https://www.cnblogs.com/cckui/p/14596109.html
Copyright © 2011-2022 走看看