场景:
每个页面都要实现分享功能,但是页面有些是用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
}