【问题标题】:Is it possible to match the # part for any route in React Router 5?是否可以为 React Router 5 中的任何路由匹配 # 部分?
【发布时间】:2020-01-22 07:59:50
【问题描述】:

在我的应用中,我想匹配所有以#something 结尾的路线。

   /map#login
   /info#login
and
   /map#register
   /map/one#register
   /info#register
   /info/two#register

所以我可以将组件显示为内容顶部的弹出窗口。如何做到这一点?

【问题讨论】:

  • 我认为 React Router 不可能。这就像同时使用BrowserRouterHashRouter

标签: reactjs hash react-router hashbang react-router-navigation


【解决方案1】:

我为这种情况找到了解决方案。它的灵感来自this question in stackOverflow。对 Route 使用 HashRoute 包装器并根据 location.hash 显示组件。

const HashRoute = ({ component: Component, hash, ...routeProps }) => (
  <Route
    {...routeProps}
    component={({ location, ...props }) =>
      location.hash === hash && <Component {...props} />
    }
  />
);

export default class App extends Component {
  constructor() {
    super();
  }

  render() {
    return (
      <div className='App'>
        <Router history={history}>
            <HashRoute hash='#login'component={Login} />
            <HashRoute hash='#register' component={Register} />

            <Switch>
              <Route exact path='/map' component={Map} />
              <Route exact path='/info' component={Info} />
            </Switch>
        </Router>
      </div>
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-11
    • 2016-12-06
    • 2023-02-17
    • 2016-04-22
    • 2016-10-09
    • 2016-09-02
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多