2016-07-20 63 views
7

在標題中,我有一個菜單按鈕,點擊時會顯示不同的鏈接。但是,我只想在主路徑中顯示菜單按鈕(即「/」)。當我導航到其他頁面時,我想將菜單按鈕更改爲後退按鈕。這個後退按鈕應該像瀏覽器後退按鈕一樣,一次返回一步,直到我回到主路徑。我怎樣才能做到這一點?我正在使用「react」:「^ 15.1.0」和「react-router」:「^ 2.5.2」。顯示返回按鈕,當瀏覽器返回按鈕不在主路徑時,返回瀏覽器後退按鈕

AppClient.js

ReactDom.render((
    <Router history={hashHistory} > 
     <Route path="/" component={App}> 
      <IndexRoute component={Home} /> 
      <Route path="home" component={Home}/> 
      ... 
      ... 
      <Route path="profile" component={Profile}> 
       <IndexRoute component={Timeline} /> 
       <Route path="timeline" component={Timeline}/> 
     </Route> 
     <Route path="login" component={Login}/> 
    </Router> 
), reactContainer) 

App.js

export default class App extends React.Component { 
    render() { 
     const _this = this; 
     return (
      <div> 
       <Header/> 
       ... 
       ... 
      </div> 
     ); 
    } 
} 

Header.js

export default class Header extends React.Component { 
    render() { 
     return(
      <header> 
       <div id="header-wrapper"> 
        <div id="nav-bar-btn" class="nav"> 

         // change Menu when its not home path that is "/" 
         <Menu> 
         // to Back 
         <Back> 

        </div> 
       </div> 
      </header> 
     ); 
    } 

} 
+0

使用'' – mmushtaq

+0

這是HTML語法.. – mmushtaq

+0

如果您也使用了redux,那麼您將通過道具獲取路由器,然後您可以簡單檢查router.location.pathname使用三元運算符來掛載'

'或''組件。其他方面,你必須聽取路線變化。 – Vikramaditya

回答

4

jsfiddle demo

import { hashHistory } from 'react-router'; 

export default class Header extends React.Component { 
    constructor(props){ 
     super(props); 
     this.state={showBack:location.hash.split('?')[0]!=="#/"}; 
     this.hook = hashHistory.listenBefore(loc=> 
      this.setState({showBack:loc.pathname!=="/"}) 
     ); 
    } 
    componentWillUnmount(){ 
     this.hook(); //unlisten 
    } 
    render() { 
     return(
      <header> 
       <div id="header-wrapper"> 
        <div id="nav-bar-btn" class="nav"> 
         {this.state.showBack? 
         <div onClick={()=>hashHistory.goBack()}>Go BACK</div> 
          : <Menu/> 
         } 
        </div> 
       </div> 
      </header> 
     ); 
    } 
} 

listenBefore手錶路徑,並決定是否顯示按鈕與否。

而且hashHistory.goBack(),工作方式類似於瀏覽器的後退按鈕

enter image description here

+0

優秀的答案,但請你通過演示如何在'react-router v4'中做到這一點來更新你的答案。 – Abhi

+0

無法讀取未定義此錯誤的屬性'listenBefore'我得到 –

相關問題