react问题录5——react实现局部刷新(antd)问题起因:学习antdUI组件库时,发现 layout 的组件例⼦中,点击左侧菜单栏没有实现 content 部分的跳转。
解决⽅法:
1.⼊⼝⽂件 src/index.tsx 使⽤ BrowserRouter 将 APP 包裹
// import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter as Router } from 'react-router-dom';
// <React.StrictMode>
<Router>
<App />,
</Router>,
// </React.StrictMode>,
);
reportWebVitals();
2. App配置 src/App.tsx 在 App 内插⼊ BasicRoute (BasicRoute 已经被Layout包装好了。)
import './App.css';
import BasicLayout from './layout/BasicLayout';
import BasicRoute from './routes/router'
function App() {
return (
<div className="App"><BasicRoute />
</div>
);
}
export default App;
3. 路由配置 src/routes/router
import React from 'react';
import { Route, Routes } from 'react-router-dom';
//引⼊布局和⼦组件
import Layout from '../layout/BasicLayout';
import Welcome from '../view/Mywelcome';
import Home from '../view/Myhome';
// //分配路由
const BasicRoute = () => (
<Layout>
<Routes>
<Route path="welcome" element={<Welcome />} />
<Route path="home" element={<Home />} /></Routes>
</Layout>
);
export default BasicRoute;
4.布局配置 src/layout/BacialLayout 在这个⽂件⾥引⽤的 antd layout和menu
import React, { Children, FC } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { Layout, Menu } from 'antd';
import Home from '../view/Myhome';
import Welcome from '../view/Mywelcome'
import './BasicLayout.css';
import BasicRoute from '../routes/router'
const BasicLayout: FC = (props) => {
const { Header, Footer, Sider, Content } = Layout;
console.log(props)
// console.log('eee');
// let search = useLocation();
// console.log(search);
// console.log('sss');
// const change = () => {
// if(search.pathname == '/home'){
// return <Home />;
// }else{
// return <Welcome />;
// }
/
/ };
return (
<Layout>
<Sider width={256} style={{ minHeight: '100vh', color: 'white' }}>
<Menu theme="dark" mode="inline">
<Menu.Item key="1">
{'home '}
<Link to="/home" />
</Menu.Item>
<Menu.Item key="2">
{'welcome '}
react router6
<Link to="/welcome" />
</Menu.Item>
</Menu>
</Sider>
<Layout>
<Header style={{ background: '#fff', textAlign: 'center', padding: 0 }}>Header</Header> <Content style={{ margin: '24px 16px 0' }}>
<div style={{ padding: 24, background: '#fff', minHeight: 360 }}>{props.children}</div> </Content>
<Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer> </Layout>
</Layout>
)
;
};
export default BasicLayout;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论