当前位置:首页 > React

react点击按钮如何跳转页面

2026-01-25 05:57:25React

使用react-router-dom实现页面跳转

安装react-router-dom库

npm install react-router-dom

在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>
  );
}

使用useNavigate钩子跳转

在函数组件中使用useNavigate

react点击按钮如何跳转页面

import { useNavigate } from 'react-router-dom';

function Home() {
  const navigate = useNavigate();

  return (
    <button onClick={() => navigate('/about')}>
      跳转到关于页面
    </button>
  );
}

使用Link组件跳转

声明式导航方式

import { Link } from 'react-router-dom';

function Home() {
  return (
    <Link to="/about">
      <button>跳转到关于页面</button>
    </Link>
  );
}

带参数的跳转

传递路由参数

react点击按钮如何跳转页面

const navigate = useNavigate();

navigate('/user/123'); // 路径参数
navigate('/profile', { state: { id: 1 } }); // 状态参数

编程式导航的其他方法

使用history对象跳转

// 在新版本中已不推荐直接使用history
navigate(-1); // 返回上一页
navigate(1); // 前进
navigate('/about', { replace: true }); // 替换当前历史记录

类组件中的跳转方法

使用withRouter高阶组件

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  handleClick = () => {
    this.props.history.push('/about');
  }

  render() {
    return <button onClick={this.handleClick}>跳转</button>;
  }
}

export default withRouter(MyComponent);

标签: 跳转按钮
分享给朋友:

相关文章

vue实现路由跳转

vue实现路由跳转

Vue 路由跳转的实现方式 在 Vue 中,路由跳转可以通过 vue-router 实现,以下是几种常见的方法: 声明式导航(模板中使用 <router-link>) 通过 <r…

css制作按钮

css制作按钮

基础按钮样式 创建一个基础的CSS按钮样式,可以通过以下代码实现。这个例子包含了按钮的基本属性,如背景色、边框、内边距和文字样式。 .button { background-color: #4…

vue实现购物按钮

vue实现购物按钮

Vue 实现购物车按钮 在 Vue 中实现购物车按钮通常需要结合组件化开发、状态管理和事件处理。以下是实现购物车按钮的常见方法: 创建购物车按钮组件 <template> &…

vue实现按钮组轮换

vue实现按钮组轮换

Vue 实现按钮组轮换的方法 在 Vue 中实现按钮组轮换功能,可以通过动态绑定数据和事件处理来实现。以下是几种常见的方法: 使用 v-for 动态渲染按钮组 通过 v-for 指令动态渲染按钮组,…

php实现页面跳转

php实现页面跳转

PHP 页面跳转方法 在 PHP 中,可以通过多种方式实现页面跳转,以下是几种常见的方法: 使用 header() 函数 header() 函数是 PHP 中最常用的跳转方法,通过发送 HTTP 头…

js实现页面跳转

js实现页面跳转

使用 window.location.href 通过修改 window.location.href 属性实现页面跳转: window.location.href = 'https://example…