通過vueReslover中間層創建用以加載react組件的vue組件
import React from 'react';
import ReactDOM from 'react-dom';
import VueWrapper from '.!vueConstructer';
const makeReactContainer =Component => {return class ReactInVue extends React.Component {static displayName =` ReactinVue$ (Component.displayName || Component.name ||'Component'}`;
constructor(props)
{ super(props); this.state ={....props, }; }
vueChildren(children) {return {render: h=> h('div', children), ; }};
render(){
const {
children,
invoker,
...rest}= this.state;
const vueChildren = this.vueChildren(children); return ( <Component{...rest}> {children &&<VueWrapper component={vueChildren}/>}
</Component> ); };};};
export default {
props: ['component', 'passedProps'],
render(h) { return h('div', {ref:'react' });} ,
methods:
{mountReactComponent(h) {
const Component = makeReactContainer(h);
const children = this.$slots.default ||{};
ReactDOM.render( <component ref={ref =>{return this.cRef = ref;}}{...this.$props.passedProps}{...this. $attrs}{...this.$listeners}{...children}/>
,this.$refs.react);},},
beforeDestroy(){ ReactDOM.unmountComponentAtNode(this.$refs.react); },
mounted() {
this.mountReactComponent( this. $props.component);
}
updated() {
if (this.$slots.default !== undefined) {
this.cRef.setState({children: this. $slots.default}); }
else { this.cRef.setState({ children: null }); }
} ,
inheritAttrs: false,
watch:{
$attrs:{
handler() { this.cRef.setState({ ..this.$attrs}); , deep: true, },
'$props.component':{handler(component)this.mountReactComponent(component);},
},
$listeners: fhandler()
{ this.cRef.setState({ ..this. $listeners });}
deep: true,
},
' $props.passedProps': {handler() {this.cRef.setState({ ...this.$props.passedProps });},
deep: true,}
首先、導入了 React 和 ReactDOM 庫,以及自忘義的 Vuelrapper 組件。
定義了一個名為 makeReactContainer 的函數,該函數接受一個 Feact 組件作為參數,并返回一個ve組件。這個函數的作用是將 React 組件轉換為 vue組件。件。我們使用 this.state 對象中的 children 和rest 屬性來決定是否渲染 Vue 組件。
makeReactContainer 函數的使用方式如下:在 ReactlnVue 類中,我們擴展了
React.Component類。這個類將 Vue 組件與React 組件混合使用。displayName 屬性用于設置 React 組件的顯示名稱。
在 ReactInVue 類的 constructor 方法中,我們設置了組件的狀態,并將傳入的 props 對象合并到狀態對象中。
vueChildren 方法用于將 Vue 組件的 children 轉換為適合在 React 組件中使用的形式。這個方法返回一個對象,其中包含一個 render 方法,該方法用于渲染 Vue 組件。
render 方法用于渲染 React 組件。在這個方法中,我們首先渲染 Vue 組件,然后渲染 React 組件。我們使用 this.state 對象中的 children 和rest 屬性來決定是否渲染 Vue 組件。
makeReactContainer 函數的使用方式如下:
makeReactContainer(VueComponent);或者class ReactComponent extends React.Component { //…}
在 Vue 組件的 mounted 生命周期鉤子中,我們調用 mountReactComponent 方法來渲染和掛載
React 組件。
mountReactComponent 方法中,我們使用
ReactDOM.render 方法來渲染和掛載 React 組件。這個方法接受一個 ref 和 props 對象作為參數,并將它們設置為 React 組件的引用和屬性。
updated 生命周期鉤子中,我們檢查
Sslots.default 是否發生變化,并將其設置為
React 組件的狀態。
inheritAttrs 屬性設置為 false,以便在 Vue 組件中正確顯示 React 組件的屬性。
使用 watch 選項來監聽 Vue 組件的屬性、props
和事件,并在它們發生變化時更新 React組件的狀態。