在标题中,我有一个菜单按钮,单击该按钮将显示要转到的不同链接.但是,我只想在主页路径中显示菜单按钮(即“/”).当我导航到其他页面时,我想将菜单按钮更改为后退按钮.这个后退按钮应该像浏览器后退按钮一样,一次一步,直到我回到主路径.我怎样才能做到这一点?我正在使用“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> ); } }
解决方法
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 watch path,并决定是否显示按钮.
而hashHistory.goBack(),就像浏览器后退按钮一样