更改路线onClick的反应

时间:2017-07-27 21:46:47

标签: javascript reactjs hyperlink routes

我需要在React中将一个导航组件包装在div中,该div充当链接/ a(我已经在导航项中嵌套了<a></a>并且可以在其中嵌套另一个<a></a>。我需要在点击这个充当包装器的最外层div时,将用户重新路由到新路由。我有多个导航部分,想要使用像onClick={this.handleNavClick(newRoute)}这样的东西但是没有取得任何成功。我是控制台记录正确的linkPath,但点击时没有任何反应。

这是我的功能:

  handleNavClick(linkPath) {
    console.log(linkPath)
    let currentPath = window.location.pathname;
    currentPath =  window.location.linkPath;
  },

以下是我尝试从导航部分重新路由的示例:

 getNavItem() {
        const currentPath = window.location.pathname;
        const reportPath = "/reporting";

        return (
          <div onClick={this.handleNavClick(dashboardsPath)}>
            <li id="nav-item-view" className={ classNames({"active": currentPath === reportPath}, "sidebar-item")}>
              <div className="active-carat"></div>
            </li>
          </div>
        );
      },

2 个答案:

答案 0 :(得分:2)

你应该尝试这样的事情:

   onClick={() => {this.handleNavClick(dashboardsPath)}}

答案 1 :(得分:1)

这是因为onClick接受了一个函数,但是你在这里传递函数的结果。

你可以做这样的事情

 getNavItem() {
    const currentPath = window.location.pathname;
    const reportPath = "/reporting";

    const handleNavClick = () => {
      let currentPath = window.location.pathname;
      currentPath =  dashboardPath;
    };

    return (
      <div onClick={handleNavClick}>
        <li id="nav-item-view" className={ classNames({"active": currentPath === reportPath}, "sidebar-item")}>
          <div className="active-carat"></div>
        </li>
      </div>
    );
  },

但是出于性能原因,我不会为每个渲染创建一个处理程序。您应该使用它自己的handleNavClick方法和dashboardPath道具创建一个NavItem组件。

相关问题