react 如何跳转页面跳转
在 React 中实现页面跳转可以通过多种方式实现,具体取决于使用的路由库或原生方法。以下是常见的几种方法:
使用 react-router-dom(推荐)
如果项目已配置 react-router-dom(v6 及以上版本),可以通过以下方式跳转:
编程式导航
通过 useNavigate Hook 实现动态跳转:
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/target-path'); // 跳转到指定路径
navigate(-1); // 返回上一页
};
return <button onClick={handleClick}>跳转</button>;
}
声明式导航
通过 <Link> 或 <NavLink> 组件实现:
import { Link } from 'react-router-dom';
function MyComponent() {
return (
<Link to="/target-path">跳转到目标页</Link>
);
}
使用 window.location(原生方法)
无需路由库时,可通过原生 API 跳转:
window.location.href = 'https://example.com'; // 完整 URL
window.location.pathname = '/target-path'; // 相对路径
使用重定向组件
在路由组件中通过 <Navigate> 实现条件跳转:

import { Navigate } from 'react-router-dom';
function ProtectedRoute({ isAuthenticated }) {
return isAuthenticated ? <Dashboard /> : <Navigate to="/login" />;
}
注意事项
- 路由库依赖:
react-router-dom需提前安装并配置路由(如<BrowserRouter>)。 - 状态传递:编程式导航可通过
state参数传递数据:navigate('/target', { state: { id: 123 } }); - 替换历史记录:使用
{ replace: true }避免保留当前页历史:navigate('/target', { replace: true });
以上方法覆盖了大多数场景,根据项目需求选择合适的方式即可。






