You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React路由实现:点击Home页面的查看菜单按钮跳转到Restaurant组件

实现Home组件跳转至Restaurant组件的方案

要完成点击「查看菜单」按钮跳转到Restaurant组件的功能,我们需要分两步走:配置React路由规则和在Home组件中添加带路由跳转的按钮。以下是详细步骤:

1. 确保已配置React Router并添加路由规则

首先,确认项目中已经安装了react-router-dom,如果没有的话先执行安装命令:

npm install react-router-dom
# 或者使用yarn
yarn add react-router-dom

接下来,在你的根组件(比如App.js)中配置路由,将Home和Restaurant组件与对应路径绑定:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import Restaurant from './Restaurant';

function App() {
  return (
    <Router>
      <Routes>
        {/* 主页路由,访问根路径时渲染Home组件 */}
        <Route path="/" element={<Home />} />
        {/* 菜单页面路由,访问/restaurant时渲染Restaurant组件 */}
        <Route path="/restaurant" element={<Restaurant />} />
      </Routes>
    </Router>
  );
}

export default App;

2. 修改Home组件添加跳转按钮

这里提供两种实现方式,你可以根据需求选择:

方式一:使用Link组件(声明式导航,推荐)

Link是React Router提供的声明式导航组件,直接绑定跳转路径即可:

import React from 'react';
import { Link } from 'react-router-dom'; // 引入Link组件

const Home = () => {
  return (
    <div className="homeMain">
      <img className="home_img" src="https://i.pinimg.com/originals/53/b5/d7/53b5d70023efa05ec6797b25df413b73.jpg"/>
      <h1 className="home_h1 text-center">Maryam's Restaurant</h1>
      {/* 添加查看菜单按钮,点击跳转到/restaurant路径 */}
      <Link to="/restaurant" className="btn btn-primary">查看菜单</Link>
    </div>
  );
};

export default Home;

方式二:使用useNavigate钩子(编程式导航,适合需要前置逻辑的场景)

如果需要在跳转前执行一些逻辑(比如日志记录、参数处理),可以使用编程式导航:

import React from 'react';
import { useNavigate } from 'react-router-dom'; // 引入useNavigate钩子

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

  const handleViewMenu = () => {
    // 这里可以添加跳转前的自定义逻辑,比如:
    // console.log('用户点击了查看菜单按钮');
    navigate('/restaurant');
  };

  return (
    <div className="homeMain">
      <img className="home_img" src="https://i.pinimg.com/originals/53/b5/d7/53b5d70023efa05ec6797b25df413b73.jpg"/>
      <h1 className="home_h1 text-center">Maryam's Restaurant</h1>
      <button onClick={handleViewMenu} className="btn btn-primary">查看菜单</button>
    </div>
  );
};

export default Home;

3. 验证功能

完成以上修改后启动项目:

  • 访问根路径/时,主页会显示「查看菜单」按钮
  • 点击按钮后会自动跳转到/restaurant路径,成功展示Restaurant组件的菜单内容

内容的提问来源于stack exchange,提问作者Maryam Naveed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:48:11