什么是HOC,以及常用的方式?

HOC定义:高阶组件(Higher - Order Component,简称 HOC)是一种在 React 中用于复用组件逻辑的高级技术。它本质上是一个函数,这个函数接收一个组件作为参数,并返回一个新的组件。返回的新组件可以在原组件的基础上添加新的功能、修改组件的行为或者修改组件的属性(props)等。

常用方式:属性代理

反向继承

import React, { Component } from "react";

export default function Hoc() {
  return (
    <div>
      属性代理
      <RedPropCard />
      <BluePropCard />
      反向继承
      <LogComponent />
    </div>
  );
}

const withCard = (color) => (Component) => {
  return (props) => {
    const hotStyle = {
      margin: "8px",
      padding: "8px",
      border: `1px solid #ccc`,
      borderRadius: "4px",
      backgroundColor: color,
    };
    const name = "高阶组件";
    return (
      <div style={hotStyle}>
        <Component {...props} color={color} name={name} />
      </div>
    );
  };
};

const PropProxy = ({ color, name }) => {
  return (
    <div>
      <h2>this is the title ---{name}</h2>
      <p>hello,my name is luyi,the backgroundColor is {color}</p>
    </div>
  );
};

const RedPropCard = withCard("red")(PropProxy);
const BluePropCard = withCard("blue")(PropProxy);

class Extending extends Component {
  componentDidMount() {
    console.log(" componentDidMount,Extends");
  }
  render() {
    return <div>Extends</div>;
  }
}

const withLog = (str) => (WarppedComponent) => {
  const didmount = WarppedComponent.prototype.componentDidMount;
  return class A extends WarppedComponent {
    componentDidMount() {
      if (didmount) {
        didmount.apply(this);
      }
      console.log(str);
    }
    render() {
      return super.render();
    }
  };
};
const LogComponent = withLog("Hello luyi")(Extending);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值