react如何编写多个页面
在 React 中实现多页面应用
React 本身是一个单页面应用(SPA)框架,但可以通过多种方式实现多页面效果。以下是几种常见的方法:
使用 React Router 实现客户端路由
安装 React Router 依赖:
npm install react-router-dom
创建路由配置文件:
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
);
}
创建对应的页面组件:
// pages/Home.js
function Home() {
return <h1>Home Page</h1>;
}
使用文件系统路由(如 Next.js)
Next.js 提供了基于文件系统的路由:

-
安装 Next.js:
npx create-next-app@latest -
在
pages目录下创建页面:pages/ index.js // 对应 / about.js // 对应 /about contact.js // 对应 /contact
每个文件导出一个 React 组件:

// pages/about.js
export default function About() {
return <h1>About Page</h1>;
}
多入口配置(Webpack)
修改 Webpack 配置创建多入口点:
// webpack.config.js
module.exports = {
entry: {
main: './src/index.js',
about: './src/about.js',
contact: './src/contact.js'
},
output: {
filename: '[name].bundle.js',
path: __dirname + '/dist'
}
};
创建对应的 HTML 模板:
<!-- about.html -->
<!DOCTYPE html>
<html>
<head>
<title>About Page</title>
</head>
<body>
<div id="root"></div>
<script src="about.bundle.js"></script>
</body>
</html>
服务端渲染(SSR)方案
使用框架如 Next.js 或 Gatsby 可以轻松实现多页面:
// Next.js 动态路由
// pages/posts/[id].js
export default function Post({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
export async function getServerSideProps({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return { props: { post } };
}
静态站点生成(SSG)
使用 Gatsby 创建静态页面:
// src/pages/about.js
import React from 'react';
const AboutPage = () => (
<main>
<h1>About Us</h1>
<p>This is the about page content.</p>
</main>
);
export default AboutPage;
每种方法适用于不同场景:React Router 适合 SPA 应用,Next.js 适合 SSR/SSG,Webpack 多入口适合传统多页面应用。选择取决于项目需求和部署环境。






