The hook used: useContext
APIs used: lazy-React
1. Create a new folder testContext under the utils folder
2. Create a new file PersonContext.js and export a Context object instance
import React from 'react'
export default React.createContext()
3. Create two pages TestA.js and TestB.js that require conditional rendering to test dynamic components
4. Create a new file Dcomponent.js for encapsulating dynamic components
Ideas:
The effect I hope to achieve is the same as Vue, pass in the component name, and react will render the corresponding component
(1) Lazy loading of components
According to the idea of Vue's dynamic component component, first introduce the components that need to be dynamically rendered
import TestA from './TestA.js'
import TestB from './TestB.js
Because the dynamic component actually renders the corresponding component according to the incoming condition (component name), if you directly import all the components that need to be dynamically rendered, it will cause unnecessary loading, so here you can optimize the lazy loading of the component, and react already has a lazy help statement A lazy-loaded React component (Note: using lazy lazy-loaded components requires Suspense tag wrapping)
import React, {lazy, Suspense} from 'react'
(2) Realize the matching of component names and components
Because the component name is passed in, a compMap object can be created, the component name is the key name of compMap, the value is the corresponding component, and the corresponding key value is rendered by the key name
const compMap = {
TestA: lazy(() => import('./TestA')),
TestB: lazy(() => import('./TestB'))
}
(3) Realize component communication
Import PersonContext.js
Use context.provider in the data provider
import React, {lazy, Suspense} from 'react'
import PersonContext from "@/component/testContext/PersonContext";
const compMap = {
TestA: lazy(() => import('./TestA')),
TestB: lazy(() => import('./TestB'))
}
function Dcomponent(props) {
console.log(props, 'Dcomponent props')
let Comp = compMap[props.compName]
return (
<>
<Suspense>
<PersonContext.Provider>
<Comp value={
{...props}}/>
</PersonContext.Provider>
</Suspense>
</>
)
}
export default Dcomponent
Use useContext in data users
TestA.js:
import React,{useContext} from 'react'
import PersonContext from "@/component/testContext/PersonContext";
function TestA() {
const {person} = useContext(PersonContext)
console.log(person, 'person')
return (
<>
<h1>我是TestA页面</h1>
<h2>个人信息</h2>
<h3>姓名:{person.name}</h3>
<h3>年龄:{person.age}</h3>
<h3>爱好:{person.hobby}</h3>
</>
)
}
export default TestA
(4) Use dynamic components
NavBar.js:
import React from 'react'
import Dcomponent from "@/component/testContext/Dcomponent";
function NavBar() {
return (
<>
<Dcomponent compName={'TestA'} person={
{name: '张三', age: 18, hobby: ['吃饭', '睡觉', '打豆豆']}}/>
</>
)
}
export default NavBar