49 lines
1.1 KiB
JavaScript
49 lines
1.1 KiB
JavaScript
import React, { Component } from 'react'
|
|
import { cloneDeep } from 'lodash'
|
|
|
|
export default class ComponentDynamic extends Component {
|
|
|
|
state = {
|
|
key: null,
|
|
component: null
|
|
}
|
|
|
|
componentDidMount() {
|
|
this.loadComponent()
|
|
}
|
|
|
|
async loadComponent() {
|
|
let component;
|
|
|
|
try {
|
|
if (this.props.is) {
|
|
if (this.props.is.constructor === Function) {
|
|
// 导入函数
|
|
component = await this.props.is()
|
|
} else {
|
|
// 导入路径,必须是src以下节点,如 pages/home
|
|
component = await import(`../../${this.props.is}`)
|
|
}
|
|
}
|
|
} catch {
|
|
component = await import(`views/error/404`)
|
|
}
|
|
|
|
this.setState({
|
|
key: Math.random().toString(16).slice(2),
|
|
component: component.default
|
|
})
|
|
}
|
|
|
|
render() {
|
|
|
|
const props = cloneDeep(this.props)
|
|
|
|
delete props.is
|
|
|
|
if (this.state.component) {
|
|
return <this.state.component key={this.state.key} {...props} />
|
|
}
|
|
return <></>
|
|
}
|
|
} |