如何使用react-router-dom实现React多组件路由及页面跳转?
Solution
First, let's fix your routing setup step by step. Here's the corrected App.js code that meets your requirements:
import React, { Component } from 'react'; import { Route, NavLink, HashRouter, Link } from "react-router-dom"; import './App.css'; import Navbar from './components/navbar'; import Content from './components/content'; import Pagination from './components/pagination'; import Matchinfo from './components/matchinfo'; class App extends Component { render() { return ( <HashRouter> {/* Wrap all routes inside HashRouter to enable routing */} <div className="App"> <div className="content"> {/* Home route: render Navbar, Content, Pagination only on exact "/" path */} <Route path="/" exact> <Navbar /> <Content /> <Pagination /> </Route> {/* Matchinfo route: render only when path is "/match" */} <Route path="/match" component={Matchinfo} /> </div> </div> </HashRouter> ); } } export default App;
Next, add a navigation link to your "查看数据" button (place this in the component where the button lives, like Content or Pagination):
// Example inside Content.js import { Link } from "react-router-dom"; function Content() { return ( <div> {/* Your existing content here */} <Link to="/match"> <button>查看数据</button> </Link> </div> ); }
Key Changes Explained:
- Wrap Routes in HashRouter: Your original code imported
HashRouterbut didn't use it. All routing components need to be nested inside a Router component to function properly. - Fix Home Route Syntax: You can't pass multiple components to the
componentprop directly. Using the children syntax (placing components inside<Route>) allows you to render multiple components for a single route. - Add
exactProp to Home Route: Withoutexact, the "/" route would match every path starting with "/" (like "/match"), causing your home components to render alongsideMatchinfo. Theexactprop ensures it only matches the exact "/" path. - Add Navigation Link: Use
Linkfromreact-router-dominstead of a regular anchor tag to navigate to/match—this prevents a full page reload, which is essential for single-page apps.
Alternative: Keep Navbar on All Pages
If you want the Navbar to be visible on both the home page and the /match page, move it outside the Route components:
<HashRouter> <div className="App"> <Navbar /> {/* Navbar renders on every page */} <div className="content"> <Route path="/" exact> <Content /> <Pagination /> </Route> <Route path="/match" component={Matchinfo} /> </div> </div> </HashRouter>
This way, users can easily navigate back to the home page using the Navbar while viewing Matchinfo.
内容的提问来源于stack exchange,提问作者stone rock
相关产品推荐
相关产品推荐

