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

-
安装Next.js:
npx create-next-app@latest -
在
pages目录下创建文件自动成为路由:
pages/index.js→/pages/about.js→/about
示例pages/about.js:

export default function About() {
return <div>About Page</div>;
}
多页面应用(MPA)配置
对于真正的多页面应用(每个页面单独构建):
-
修改webpack配置:
module.exports = { entry: { home: './src/home.js', about: './src/about.js' }, output: { filename: '[name].bundle.js', path: __dirname + '/dist' } }; -
创建多个HTML文件,分别引用不同的入口文件。
静态站点生成(SSG)
使用Gatsby或Next.js的静态生成功能:
// Next.js示例
export async function getStaticPaths() {
return {
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
fallback: false
};
}
关键注意事项
- 客户端路由不会真正刷新页面,适合SPA
- 文件系统路由需要特定框架支持
- 真正的MPA需要构建工具特殊配置
- 考虑SEO时,SSG或SSR可能更合适
根据项目需求选择合适的方法,React生态提供了多种实现多页面体验的解决方案。






