【问题标题】:React Router Navbar depending on route根据路由反应路由器导航栏
【发布时间】:2020-10-27 10:04:30
【问题描述】:

我正在尝试根据我的 React 应用程序中的当前路径设置导航栏链接的样式,如果路径是 /create 或 /add 它应该改变它的样式。这是我的标题组件中到目前为止的内容:

          <div
            id="createLink"
            className={this.state.createClassName}
            onClick={() => this.handleModalToggle()}
          >
            CREATE
          </div>

  handleActiveLink= () => {
    let path = this.props.location.pathname
     if (path === "/add" | path === "/create") {
       this.setState({createClassName: "nav-link-active"})
     } else {
       this.setState({ createClassName: "nav-link" })
     }
  };

  componentDidMount() {
    this.handleActiveLink()
  }

这有效,但只有在我刷新页面后才有意义,但这不是我想要的。所以我正在寻找一种在渲染之前更改 className 并首先获取路径的方法(我正在使用 react-router-dom 中的 withRouter)

【问题讨论】:

  • react-router-dom 内置了将活动类设置为活动路由的功能。请改用NavLinkgithub.com/ReactTraining/react-router/blob/master/packages/…
  • reactrouter.com/web/api/NavLink 并添加一些逻辑来设置activeClassName。不要重新发明轮子并添加更多。
  • 我避免使用 NavLink,因为它需要一个重定向路径。在我的情况下,我只想打开一个模式来选择一些选项(创建或添加一个条目),然后将用户重定向到 /create 或 /add
  • 在这种情况下,我建议不要将此类瞬态数据存储在 state 中,它可以简单地从 props 派生并设置为 className渲染函数。

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


【解决方案1】:

问题似乎是您只在组件安装时检查路径,而不是在更新时检查路径。您还应该签入componentDidUpdate

handleActiveLink= () => {
  let path = this.props.location.pathname;
  if (path === "/add" || path === "/create") {
    this.setState({createClassName: "nav-link-active"});
  } else {
    this.setState({ createClassName: "nav-link" });
  }
};

componentDidMount() {
  this.handleActiveLink();
}

componentDidUpdate() {
  this.handleActiveLink();
}

在这种情况下,我建议 不要 将此类瞬态数据存储在 state 中,只需从 props 派生它并在渲染函数中设置为 className(或任何地方)你渲染它)。这样,它会计算每次渲染何时 UI 将被某些东西更新并且将始终是最新的(即您无需担心生命​​周期函数)。

render() {
  const { location: { pathname } } = this.props;
  const linkClass = ["/add", "/create"].includes(pathname)
    ? "nav-link-active"
    : "nav-link";

  ...

  <div
    id="createLink"
    className={linkClass}
    onClick={() => this.handleModalToggle()}
  >
    CREATE
  </div>
  ...
}

【讨论】:

  • 像魅力一样工作。还有非常优雅的代码,非常感谢!
猜你喜欢
  • 2020-12-31
  • 2016-04-09
  • 2016-04-10
  • 2021-03-29
  • 2021-03-17
  • 1970-01-01
  • 2017-06-24
  • 2018-09-04
  • 1970-01-01
相关资源
最近更新 更多