2017-07-27 43 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組件。