React in Vue3

313 阅读1分钟

定义

// reactInVue.ts
import { defineComponent, h, onMounted, onUnmounted, ref } from 'vue'
import ReactDOM from 'react-dom/client'
import {
  ComponentClass,
  createElement,
  FunctionComponent,
  ReactInstance,
} from 'react'

export default (
  component: string | FunctionComponent<{}> | ComponentClass<{}, any>
) =>
  defineComponent({
    inheritAttrs: false,
    setup(props, { attrs }) {
      const root = ref()
      onMounted(() => {
        root.value = ReactDOM.createRoot(document.getElementById('react-root')!)
        root.value.render(createElement(component, attrs))
      })
      onUnmounted(() => {
        root.value?.unmount()
      })

onUpdated(() => {
               root.value.render(createElement(component, attrs))
      })

      return () => h('div', { id: 'react-root' })
    },
  })

使用

<template>
 <MyDateRangePicker
          :ranges="dates"
          :editableDateInputs="true"
          showSelectionPreview
          :moveRangeOnFirstSelection="false"
          :onChange="onDateChange"
          :scroll="{ enabled: true }"
          :months="2"
        />
</template>
<script lang='ts' setup>
import { DateRangePicker } from 'react-date-range'
import { addDays } from 'date-fns'

import 'react-date-range/dist/styles.css' // main style file
import 'react-date-range/dist/theme/default.css' // theme css file

const MyDateRangePicker = reactInVue(DateRangePicker)

const dates = ref([
  {
    startDate: new Date(),
    endDate: addDays(new Date(), 7),
    key: 'selection',
  },
])
const onDateChange = (item) => {
  dates.value = [item.selection]
}
</script>