react高阶组件:如何同时兼容class类组件和函数式组件。

场景:

每个页面都要实现分享功能,但是页面有些是用class类,有些又直接是函数式。

方案1: 写2套方法。各自引用。(维护不太好,改要改2遍)

方案2: 可以封一个 jsx的组件,假如名为<Share>。返回一个<><>,在每个页面render或者 return里面引用<Share>

方案3:目前在用的,直接贴代码:

通过判断组件的类型,继承不同的原型。

/*
 * @Date: 2024-03-04 16:10:22
 * @Description: 右上角分享的钩子函数
 */

import React from 'react'

export function isClassComponent(component) {
  return (
    typeof component === 'function' && !!component.prototype.isReactComponent
  )
}

export default function withShare(Component) {
  const classComponent = class ContainerBox extends Component {
    /** 分享到聊天框 */
    onShareAppMessage() {
      const url = '/pages/home/index'
      const title = 'title'
      const shareData: any = {
        title: this.props?.title || title,
        path: this.props?.url || url,
        imageUrl: $.cdn('ypdj_mini_share.png'),
      }
      if (this.props?.img) {
        shareData.imageUrl = this.props.img
      }
      return shareData
    }

    /** 分享到朋友圈 */
    onShareTimeline() {
      const title = '全国家居售后服务平台'
      const shareData: any = {
        title: this.props?.title || title,
      }
      if (this.props?.img) {
        shareData.imageUrl = this.props.img
      }
      return shareData
    }
  }

  const functionComponent = class ContainerBox extends React.PureComponent<any> {
    /** 分享到聊天框 */
    onShareAppMessage() {
      const url = '/pages/home/index'
     const title = 'title'
      const shareData: any = {
        title: this.props?.title || title,
        path: this.props?.url || url,
        imageUrl: $.cdn('ypdj_mini_share.png'),
      }
      if (this.props?.img) {
        shareData.imageUrl = this.props.img
      }
      return shareData
    }

    /** 分享到朋友圈 */
    onShareTimeline() {
      const title = 'title'
      const shareData: any = {
        title: this.props?.title || title,
      }
      if (this.props?.img) {
        shareData.imageUrl = this.props.img
      }
      return shareData
    }

    render(): React.ReactNode {
      return (
        <Component {...this.props}></Component>
      )
    }
  }

  if (isClassComponent(Component)) {
    return classComponent
  }
  return functionComponent
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值