react 如何实现多页面
实现多页面的方法
在React中实现多页面应用(MPA)通常需要结合路由工具或构建工具配置。以下是几种常见方法:
使用React Router
React Router适合单页应用(SPA),但可以通过动态加载实现多页面的效果。安装React Router:
npm install react-router-dom
配置基本路由:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage} />
<Route path="/contact" component={ContactPage} />
</Switch>
</Router>
);
}
使用Webpack多入口配置
通过Webpack配置多个入口点生成独立页面。修改webpack.config.js:
module.exports = {
entry: {
home: './src/home/index.js',
about: './src/about/index.js',
},
output: {
filename: '[name].bundle.js',
path: __dirname + '/dist',
}
};
每个入口对应独立的HTML模板:
new HtmlWebpackPlugin({
template: './src/home/index.html',
filename: 'home.html',
chunks: ['home'],
}),
new HtmlWebpackPlugin({
template: './src/about/index.html',
filename: 'about.html',
chunks: ['about'],
})
使用Next.js框架
Next.js内置多页面支持,文件系统即路由。在pages目录下创建文件自动生成路由:
pages/
index.js → /
about.js → /about
contact.js → /contact
每个文件导出React组件:
function AboutPage() {
return <div>About Page</div>;
}
export default AboutPage;
服务端渲染(SSR)方案
使用Express或Koa等Node框架处理多页面请求:

const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/home.html');
});
app.get('/about', (req, res) => {
res.sendFile(__dirname + '/views/about.html');
});
注意事项
- 静态资源路径需使用绝对路径避免404错误
- 多页面应用可能导致状态共享困难,需考虑使用状态管理工具
- 页面跳转会触发完整刷新,与SPA体验不同






