使用react如何跳转页面跳转
使用 React Router 进行页面跳转
React 应用中通常使用 react-router-dom 库实现页面跳转。以下是几种常见的跳转方式:
安装 react-router-dom
npm install react-router-dom
使用 <Link> 组件跳转
<Link> 是 React Router 提供的导航组件,用于声明式跳转,不会触发页面刷新。
import { Link } from 'react-router-dom';
function NavBar() {
return (
<nav>
<Link to="/home">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}
使用 useNavigate Hook 跳转
useNavigate 是 React Router v6 提供的 Hook,用于编程式导航。

import { useNavigate } from 'react-router-dom';
function LoginButton() {
const navigate = useNavigate();
const handleLogin = () => {
navigate('/dashboard');
};
return <button onClick={handleLogin}>Login</button>;
}
使用 history.push(v5 及以下版本)
React Router v5 及以下版本使用 history 对象进行跳转。
import { useHistory } from 'react-router-dom';
function BackButton() {
const history = useHistory();
const goBack = () => {
history.push('/previous-page');
};
return <button onClick={goBack}>Go Back</button>;
}
路由配置示例
确保在根组件中配置路由,以支持跳转功能。
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
跳转时传递参数
可以通过 URL 参数或状态传递数据。

URL 参数
navigate('/user/123');
状态传递
navigate('/user', { state: { id: 123 } });
在目标组件中通过 useLocation 获取状态:
import { useLocation } from 'react-router-dom';
function UserPage() {
const location = useLocation();
const { id } = location.state;
}
总结
- 使用
<Link>进行声明式跳转。 - 使用
useNavigate进行编程式跳转(v6 及以上版本)。 - 使用
useHistory进行编程式跳转(v5 及以下版本)。 - 配置路由以支持页面跳转。
- 通过 URL 参数或状态传递数据。





