【问题标题】:Change route onClick of div react更改 div react 的 onClick 路由
【发布时间】:2018-01-03 19:38:53
【问题描述】:

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

这是我的功能:

  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>
        );
      },

【问题讨论】:

    标签: javascript reactjs hyperlink routes


    【解决方案1】:

    你应该尝试这样的事情:

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

    【讨论】:

    【解决方案2】:

    这是因为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 组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多