React Router - NavLink activeStyle 或 activeClassName 不适用于嵌套路由

React Router - NavLink activeStyle or activeClassName not working for nested routes

我正在使用 react-router-dom。在我的代码中,NavLink 无法应用 activeStyleactiveClassName 甚至在页面 load/reload 上也不行。我嵌套了路由但没有使用 redux。

示例代码: Stackblitz

react-router-dom 版本:4.3.1

index.js:

  render() {
    return (
      <div>
        <Router>
          <Hello>
            <Route path="/child-a" component={ChildA} />
            <Route path="/child-b" component={ChildB} />
          </Hello>
        </Router>
      </div>
    );
  }

hello.js:

  render() {
    return (
      <div>
        <h5>
          <NavLink
            to="child-a"
            activeStyle={{ color:'red' }}
            exact
          >child-a</NavLink>
        </h5>
        <h5>
          <NavLink
            to="child-b"
            activeStyle={{ color:'red' }}
            exact
          >child-b</NavLink>
        </h5>
        <div>
          <div><h2>Hello</h2></div>
          {this.props.children}
        </div>
      </div>
    );
  }

尝试在 to 属性.

前加一个斜杠

hello.js更改为:

render() {
    return (
      <div>
        <h5>
          <NavLink
            to="/child-a"
            activeStyle={{ color:'red' }}
            exact
          >child-a</NavLink>
        </h5>
        <h5>
          <NavLink
            to="/child-b"
            activeStyle={{ color:'red' }}
            exact
          >child-b</NavLink>
        </h5>
        <div>
          <div><h2>Hello</h2></div>
          {this.props.children}
        </div>
      </div>
    );
  }

似乎对我有用!

NavLink activeStyle 不适用于嵌套路由。由于您使用的是 react-router-dom,因此您可以利用另一个 属性 history

反应路由器Docs

history objects typically have the following properties and methods: location - (object) The current location. May have the following properties: pathname - (string) The path of the URL

hello.js:

import { Link, withRouter } from "react-router-dom";

const activeTab = (history, path) => {
  if (history.location.pathname === path) {
    return { color: "red" };
  }
};

const Hello= ({ history }) => {
render() {
    return (
      <div>
        <h5>
          <Link
            to="/child-a"
            style={activeTab(history, "/child-a")}
            exact
          >child-a</Link>
        </h5>
        <h5>
          <Link
            to="/child-b"
            style={activeTab(history, "/child-b")}
            exact
          >child-b</Link>
        </h5>
        <div>
          <div><h2>Hello</h2></div>
          {this.props.children}
        </div>
      </div>
    );
  }
}
export default withRouter(Hello);