React 高阶组件(HOC)

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, width: 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;
};
 

posted on   漫思  阅读(1)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2023-02-15 “开源 core-js 也许是我一生中最大的错误”
2023-02-15 如何解决Reporting Services目录数据库文件存在的问题
2023-02-15 怎么处理Reporting Services目录数据库文件存在的问题?
2023-02-15 Redis配置以及通过C#访问小试
2023-02-15 从 Newtonsoft.Json 迁移到 System.Text.Json
2023-02-15 动态Entity Framework查询:Dynamic Query 介绍
2023-02-15 asp.net 开发优秀博客

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示