前言
最近有个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>