2016-07-20 65 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'我得到 –

相关问题