React框架使用vue3组件

前言

        最近有个React项目,要求加几个抽奖组件,百度找了个NutUI-Bingo组件库。

        这个组件库是用vue3写的,研究了半天终于搞懂怎么在React框架里面用vue组件,写个文章记录一下。

首先,安装必要的依赖

          首先,在项目中安装必要的依赖,包括vue和@vue/reactivity

npm install vue @vue/reactivity

接下来,引入一个vue3组件

        比如NutUI-Bingo组件库里的Hiteggs(砸金蛋)

import React from 'react'
import { createApp, h } from 'vue'
import { Hiteggs } from "@nutui/nutui-bingo";
import "@nutui/nutui-bingo/dist/style.css";

interface GoldenType {
  items?: Array<any>;
  dots?: boolean; //是否显示面板指示点
  vertical?: boolean; //垂直显示
  infinite?: boolean;  //是否循环播放
  type?: 'prize' | 'carousel'
  height?: string;
  onLoadData?: () => Promise<any>;
  eggProps?: any
}

const handleClick = () => {
  console.log('点击事件') // 在 React 组件中处理点击事件
}

class HitEgg extends React.Component<GoldenType> {
  containerRef = React.createRef<HTMLDivElement>();
  appInstance: any = null; // 保存应用程序实例的引用

  componentDidMount() {
    this.createAppInstance();
  }

  componentDidUpdate(prevProps: GoldenType) {
    if (this.props !== prevProps) {
      this.updateAppInstance();
    }
  }

  createAppInstance() {
    if (this.containerRef.current) {
      this.appInstance = createApp({
        render: () =>
          h(Hiteggs, {
            num: this.props.eggProps.numEgg || 1,
            intactImg: this.props.eggProps.imgEgg[0].url,
            splitImg: this.props.eggProps.imgSplit[0].url,
            hammer: this.props.eggProps.imgHammer[0].url,
            width: '80px',
            height: '80px',
            onClick: handleClick
          }),
      });

      this.appInstance.mount(this.containerRef.current);
    }
  }

  updateAppInstance() {
    if (this.appInstance && this.containerRef.current) {
      this.appInstance.unmount(); // 卸载之前的应用程序实例
    }

    this.createAppInstance();
  }

  componentWillUnmount() {
    if (this.appInstance) {
      this.appInstance.unmount();
    }
  }

  render() {
    return <div ref={this.containerRef} />;
  }
}
export default HitEgg

最后调用就行了

import HitEgg from '@/components/hitegg';
      <HitEgg
        items={props.items}
        onLoadData={onLoadData}
        eggProps={props}
      >
      </HitEgg>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值