我有一个使用 react-router-dom v4
工作的基本路由 SPA我想获取当前路由(路径名)用于我的标题(应用程序的外部上下文 - 不确定这是否是准确的命名法)。我想在我的应用程序栏中有一个按钮,它会根据当前使用的路线执行某些操作。
index.js
ReactDOM.render((
<MuiThemeProvider>
<div>
<Router history={history}>
<div>
<Header />
<MainView />
</div>
</Router>
</div>
</MuiThemeProvider>
), document.getElementById('app'));
header.js
class Header extends React.Component {
constructor(props){
super(props);
this.state = {
open: false
};
}
toggleDrawer(){
this.setState({open: !this.state.open}, ()=> {console.log(this.state)});
}
render() {
return (
<div>
<AppBar
iconClassNameRight="muidocs-icon-navigation-expand-more"
onLeftIconButtonTouchTap={()=>{this.toggleDrawer()}}
iconElementRight={<FlatButton label="Create New"/>}
/>
...
在header.js
我想访问路由的路径名以从 <FlatButton />
调用某个函数在应用栏的右侧。我试过了 {this.props.location.pathname}
根据 v4 文档,但只有错误。 TBH 不过我可能用错了。
最佳答案
该 Prop 仅提供给作为 Route
子项呈现的组件。如果你想在其他地方(比如在你的页眉中),你可以使用 withRouter将 Prop 注入(inject)组件的辅助方法:
// Header.js
import { withRouter } from 'react-router';
// private header class
class Header extends React.Component {
render() {
// you can access this.props.location here
}
}
// wrap Header class in a new class that will render the
// Header class with the current location
// export this class so other classes will render this
// wrapped component
export default withRouter(Header);
// index.js
// ....
ReactDOM.render((
<MuiThemeProvider>
<div>
<Router history={history}>
<div>
<Header />
<MainView />
</div>
</Router>
</div>
</MuiThemeProvider>
), document.getElementById('app'));
关于javascript - 在 react 中全局获取路由的路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43989165/