在React路由器中使用具有404页的多个布局,可以通过以下步骤实现:
npm install react-router-dom
DefaultLayout
的默认布局组件和一个名为ErrorLayout
的错误布局组件。import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import DefaultLayout from './DefaultLayout';
import ErrorLayout from './ErrorLayout';
import HomePage from './HomePage';
import AboutPage from './AboutPage';
import NotFoundPage from './NotFoundPage';
const App = () => {
return (
<Router>
<Switch>
<Route exact path="/" render={() => <DefaultLayout><HomePage /></DefaultLayout>} />
<Route path="/about" render={() => <DefaultLayout><AboutPage /></DefaultLayout>} />
<Route render={() => <ErrorLayout><NotFoundPage /></ErrorLayout>} />
</Switch>
</Router>
);
}
export default App;
import React from 'react';
import Navbar from './Navbar';
import Footer from './Footer';
const DefaultLayout = ({ children }) => {
return (
<div>
<Navbar />
<div className="content">
{children}
</div>
<Footer />
</div>
);
}
export default DefaultLayout;
import React from 'react';
const ErrorLayout = ({ children }) => {
return (
<div>
<h1>404 Page Not Found</h1>
{children}
</div>
);
}
export default ErrorLayout;
HomePage
和AboutPage
,并在这些组件中编写相应的内容。import React from 'react';
const HomePage = () => {
return (
<div>
<h1>Welcome to the Home Page</h1>
{/* Add your content here */}
</div>
);
}
export default HomePage;
import React from 'react';
const AboutPage = () => {
return (
<div>
<h1>About Us</h1>
{/* Add your content here */}
</div>
);
}
export default AboutPage;
NotFoundPage
,并在其中编写页面不存在时的内容。import React from 'react';
const NotFoundPage = () => {
return (
<div>
<h1>Oops! Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
</div>
);
}
export default NotFoundPage;
通过以上步骤,你可以在React路由器中使用具有404页的多个布局。根据路由规则,当用户访问不存在的页面时,将显示错误布局组件中的404页面。对于其他页面,将显示默认布局组件中的相应页面内容。这样可以实现不同页面布局的灵活切换和404页面的定制化展示。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云