【问题标题】:react-router-dom conditional renderingreact-router-dom 条件渲染
【发布时间】:2018-05-27 22:56:45
【问题描述】:

我想在路由路径为“/flower”时添加更多代码

所以我的代码如下。

[App.js]

class App extends Component {
  render() {
    return (
      <Router>
      <div className="App">
        <Header />
        <SideBar />
        <section>
          <Route exact path="/" component={Home} />
          <Route exact path="/flower" component={Flower} />
          <Route exact path="/editorial" component={Editorial} />
        </section>
        <Footer />
      </div>
      </Router>
    );
  }
}

[SideBar.js]

import React, { Component } from 'react';
import './index.css';
import { NavLink } from 'react-router-dom';

class index extends Component {
    render() {
        return (
            <aside>
                <NavLink exact to="/" className="item"><i className="fas fa-home"></i>HOME</NavLink>
                <NavLink to="/flower" className="item"><i className="fab fa-pagelines"></i>FLOWER</NavLink>
                <NavLink to="/editorial" className="item"><i className="fas fa-newspaper"></i>EDIT</NavLink>

            </aside>
        );
    }
}

除了/flower,所有页面的侧边栏都是一样的。

当用户输入 /flower 时,我想在我的 SideBar 添加更多代码。

[不是/花]

[用户进入/flower]

但是,我不知道如何检测当前路径是 /flower。

有什么解决办法或指导方针吗?

谢谢。

【问题讨论】:

  • 我想我必须使用 props.location.pathname 进行操作,但是 SideBar 中不存在该道具,而是在 Home、Flower、Edit 组件中。那么我怎样才能在 SideBar 中访问该道具或以任何方式对其进行操作呢?
  • 为什么不在SideBar 中使用Route?喜欢&lt;Route exact path="/flower" component={SideBarFlower}/&gt;
  • @Oblosys 这不是一件重要的事情。也无法访问路径名。
  • 不明白你所说的“不重要”是什么意思。您可以简单地访问SideBarFlower 中的路线道具,但从您的问题来看,您并不清楚为什么需要这样做。
  • @Oblosys 我只想在用户只能访问 /flower 时向 SideBar 添加更多子菜单、按钮等。但目前在我的代码中,SideBar 没有路径名道具。所以我很困惑如何解决它。

标签: reactjs react-router-dom


【解决方案1】:

但是,我不知道如何检测到当前路径是 /flower。

但是你已经用Route 做到了这一点:)

<Route exact path="/" component={Home} />
<Route exact path="/flower" component={Flower} />
<Route exact path="/editorial" component={Editorial} />

您根据当前路径有条件地渲染组件。所以HomeFlowerEditorial 将被呈现如果 当前 URL 路径与您传递给 Routepath 匹配器匹配。

您可以在侧边栏中执行完全相同的操作:

<aside>
   <NavLink exact to="/" className="item"><i className="fas fa-home"></i>HOME</NavLink>
   <NavLink to="/flower" className="item"><i className="fab fa-pagelines"></i>FLOWER</NavLink>
   <NavLink to="/editorial" className="item"><i className="fas fa-newspaper"></i>EDIT</NavLink>

   <Route 
     path="/flower" 
     render={() => (
       <div>
        <p>more stuff</p>
       </div>
     )} 
   />
</aside>

我使用了render,但您可以像在其他Routes 中一样使用component 属性。

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 2020-03-30
    • 2019-01-15
    • 2018-12-13
    • 2017-11-14
    • 1970-01-01
    • 2021-03-26
    • 2022-06-16
    • 2022-07-28
    相关资源
    最近更新 更多