2017-07-27 126 views
1

我需要在React中包装一个导航组件作为链接/ a(我已经有一个<a></a>嵌套在导航项目中,并且可以嵌套另一个<a></a>。将用户路由到一个新的路线,点击这个最外面的div,它充当包装。我有多个导航部分,并且想要使用类似于onClick={this.handleNavClick(newRoute)}的东西,但没有取得任何成功。发生在点击更改路线onClick作出反应

这里是我的功能:

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

这里是一个考试我的PLE试图重新路线从导航部分:

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

你应该尝试这样的事:

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

我建议[反对这虽然](https://stackoverflow.com/questions/36677733/why-jsx-props-should-not-use -arrow-functions) – Ezz

+0

@Ezz是的,你是对的。但Facebook在其文档中确认了这种方法。 https://facebook.github.io/react/docs/handling-events.html所以没关系,如果我们没有任何性能问题。 –

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 prop创建一个NavItem组件。