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

问题描述 投票:0回答:1

我正在使用react-router-dom。在我的代码中,NavLink无法在页面加载/重新加载时应用activeStyleactiveClassName。我已经嵌套了路由但没有使用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>
    );
  }
reactjs react-router react-router-v4 react-router-dom
1个回答
1
投票

尝试在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>
    );
  }

似乎为我工作!

© www.soinside.com 2019 - 2024. All rights reserved.