javascript - 在 react 中全局获取路由的路径名

标签 javascript reactjs

我有一个使用 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/

相关文章:

javascript - 无法清除计时器数组内的计时器

javascript - Jqgrid - 如何更改禁用/灰色文本颜色

javascript - 如何捕获和解析从 Google Maps v3 API 返回的 JSON?

javascript - 递归、Node js 和异步调用

reactjs - 如何使用 React 和 TypeScript 修复错误 "cannot invoke an object which is possibly undefined"?

javascript - 如何更改 OpenLayers 5.3 的图 block 语言

javascript - 通过组件向ReactJs函数发送数据

javascript - 如何从 defaultProps 迁移到默认参数

facebook - React JS加载FB分享

javascript - react-dates 组件不允许选择当前日期之前的日期