React使用react-router-dom如何实现指定路由页面隐藏导航菜单
你当前的代码把<Nav />导航组件放在了所有路由规则的外层,属于全局公共渲染内容,所以无论访问哪个路径,导航都会显示。
解决方案1(最简单,推荐新手使用)
利用react-router-dom自带的<Route>组件的路径匹配特性控制导航的渲染,只有匹配到指定路径时才渲染Nav组件:
- 仅首页显示导航:把原来的
<Nav />替换为<Route exact path="/" component={Nav} />即可 - 多个指定页面显示导航:给Route的path属性传路径数组,后续新增/删除显示导航的页面只需修改数组即可,适配你最多20个导航链接的需求:
<Route path={["/", "/services", "/contact"]} exact component={Nav} />
改完后的完整代码如下:
// 删掉重复导入的React import React, { Component } from 'react'; import './style.css'; import { render } from 'react-dom'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; const Nav = () => ( <div> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </div> ); const HomePage = () => <h1>Home Page</h1>; const AboutPage = () => <h1>About Page</h1>; export default class App extends Component { constructor() { super(); this.state = { name: 'React', }; } render() { return ( <Router> {/* Router组件仅允许有1个子元素,本示例使用简单div元素包裹 */} <div> {/* 仅匹配到路径数组里的路径时才渲染Nav */} <Route exact path={["/"]} component={Nav} /> <Route exact path="/" component={HomePage} /> <Route path="/about" component={AboutPage} /> </div> </Router> ); } } render(<App />, document.getElementById('root'));
解决方案2(灵活度更高,适合黑名单控制场景)
如果你是要指定少数页面隐藏导航,剩下的所有页面都显示,可以用withRouter高阶组件给App注入路由信息,通过当前路径判断是否渲染导航:
import React, { Component } from 'react'; import './style.css'; import { render } from 'react-dom'; import { BrowserRouter as Router, Route, Link, withRouter } from 'react-router-dom'; const Nav = () => ( <div> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </div> ); const HomePage = () => <h1>Home Page</h1>; const AboutPage = () => <h1>About Page</h1>; class App extends Component { constructor() { super(); this.state = { name: 'React', // 配置需要隐藏导航的路径 hideNavPaths: ["/about"] }; } render() { const currentPath = this.props.location.pathname; const showNav = !this.state.hideNavPaths.includes(currentPath); return ( <div> {showNav && <Nav />} <Route exact path="/" component={HomePage} /> <Route path="/about" component={AboutPage} /> </div> ); } } // 用withRouter包裹App,注入路由相关属性 const AppWithRouter = withRouter(App); // 外层包裹Router render(<Router><AppWithRouter /></Router>, document.getElementById('root'));
内容的提问来源于stack exchange,提问作者HelloWorld1
相关产品推荐
相关产品推荐

