【问题标题】:How to add class to nav when current url=link to in react-router-dom当前url =链接到react-router-dom时如何将类添加到导航
【发布时间】:2019-08-03 06:17:26
【问题描述】:

我正在尝试做一个如下所示的基本路由器网站。当“to”与当前 url 路径匹配时,我想向元素添加一个“selected”类(因此它可以突出显示活动链接)。

我看不到如何将位置放入 App 道具中,因此我可以使用该位置来更改样式。

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import "./App.scss";

function About() {
  return <h2>About</h2>;
}

function Projects() {
  return <h2>Projects</h2>;
}
function EmailList() {
  return <h2>EmailList</h2>;
}

function App(props) {
  console.log(props);
  return (
    <Router>
      <div id="router">
        <div id="nav">
          <Link id="about-link" className="" to="/">
            <div className="circle icon-about">
              <span>About</span>
            </div>
          </Link>
          <Link id="projects-link" className="selected" to="/projects/">
            <div className="circle icon-projects">
              <span>Projects</span>
            </div>
          </Link>
          <Link id="writing-link" to="/writing/">
            <div className="circle icon-writing">
              <span>Writing</span>
            </div>
          </Link>
          <Link id="mailing-list-link" to="/email-list/">
            <div className="circle icon-email-list">
              <span> Mailing List</span>
            </div>
          </Link>
        </div>
        <div id="content">
          <Route path="/" exact component={About} />
          <Route path="/projects/" component={Projects} />
          <Route path="/email-list/" component={EmailList} />
        </div>
      </div>
    </Router>
  );
}

export default App;

【问题讨论】:

标签: reactjs react-router react-router-dom


【解决方案1】:

如何在 App 内查看window.location.pathname

【讨论】:

    【解决方案2】:

    你可以使用

    <NavLink to="/" activeClassName="selected"> FAQs </NavLink>

    而不是&lt;Link&gt;

    https://reacttraining.com/react-router/web/api/NavLink

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 1970-01-01
      • 2017-09-21
      • 2016-03-28
      • 1970-01-01
      • 2017-09-08
      • 2016-04-24
      • 2021-05-07
      • 1970-01-01
      相关资源
      最近更新 更多