两种页面嵌套的方式,一种是父子组件,一种是懒加载
1、父子组件(可略,只用来做例子对比)
原本需要用父子组件来实现页面嵌套,如果嵌套的组件不多,可以这样实现
父页面
import React,{Component} from "react";
import {Button} from "antd"
import LazyLoadsOne from './LazyLoadsOne' //直接导入子组件
import LazyLoadsTwo from './LazyLoadsTwo'
class LazyLoads extends Component{
constructor(props){
super(props);
this.state = {
visible:true,
}
}
genghuanZujian=(vis)=>{
this.setState({visible:!vis})
}
render() {
const {visible} =this.state;
return(
<div>
<h2>这是父组件</h2>
<Button type="primary" onClick={()=>{this.genghuanZujian(visible)}} >普通更换组件</Button>
{visible&&<LazyLoadsOne/>}
{!visible&&<LazyLoadsTwo/>}
</div>
)
}
}
export default LazyLoads;
子页面
import React from "react";
const LazyLoadsOne = ()=>{
return(
<div>
<h2>
这是子页面One
</h2>
</div>
);
};
export default LazyLoadsOne;
import React from "react";
const LazyLoadsTwo = ()=>{
return(
<div>
<h2>
这是子页面Two
</h2>
</div>
);
};
export default LazyLoadsTwo;
2、使用懒加载
1、新建一个文件PageUtil.js,用于存放子组件地址
export function getPage(pageCode) {
switch (pageCode) {
case 'LazyLoadsOne':
return React.lazy(()=>import('./LazyLoadsOne'));
case 'LazyLoadsTwo':
return React.lazy(()=>import('./LazyLoadsTwo'));
case 'LazyOne':
return React.lazy(()=>import('./LazyOne'));
case 'LazyTwo':
return React.lazy(()=>import('./LazyTwo'));
default:
return null;
}
}
父页面
import React,{Component,Suspense,useRef} from "react";
import {Button,Spin,Form,Input} from "antd"
import {getPage} from './PageUtil'
class LazyLoads extends Component{
constructor(props){
super(props);
this.form = React.createRef();
this.state = {}
}
lazyGenghuanZujian=()=>{
//当使用一个在浏览器中不存在的标签或以小写开头的组件名时,会报"The tag is unrecognized in this browser"React警告。
//组件名首字母大写是React用来区分我们编写的组件和存在于浏览器中的内置标签的惯例
const Zujian = getPage('LazyOne');//这样就能根据条件动态获取子组件
this.setState({
pageContent :<Zujian ref={(e)=>{this.page=e}} />
})
}
render() {
const {pageContent} = this.state;
return(
<div>
<h2>这是父组件</h2>
<Form ref={this.form} name="control-hooks" onFinish={this.lazyGenghuanZujian}>
<Form.Item label="请输入加载模块:" name="id">
<Input/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">懒加载更换组件</Button>
</Form.Item>
</Form>
<Suspense fallback={<Spin/>} >
{pageContent}
</Suspense>
</div>
)
}
}
export default LazyLoads;