问题
In my app, I'd like to match both the path and the hash to different components. For example:
/pageA#modalB
Would show PageA as the main page, with modalB over the top. I've tried the following, with many variations of the path property:
<Route path="#modalB" component={modalB}/>
But nothing works.
In React Router 2 inside a modal 'controller' component, I would use:
browserHistory.listen( (location) => { //do something with loction.hash })
I was hoping for something a little more elegant in V4
回答1:
Not out of the box, but the beauty of React Router 4 is that it's incredibly easy to implement this yourself.
let HashRoute = ({ component: Component, path, ...routeProps }) => (
<Route
{...routeProps}
component={({ location, ...props }) =>
location.hash === path && <Component {...props} />
}
/>
)
<HashRoute path="#modalB" component={ModalB} />
回答2:
@azium answer works fine as long as you don't need to use render or children prop in HashRoute. In which case this solution will work better :
import React from 'react';
import { Route } from 'react-router-dom';
const HashRoute = ({ hash, ...routeProps }) => (
<Route
render={({ location }) => (
(location.hash === hash) && <Route {...routeProps} />
)}
/>
);
export default HashRoute;
Use it like that :
<HashRoute hash="#modalB" component={ModalB} />
Or combine it with route matching :
<HashRoute hash="#modalB" path="/subPageOnly" component={ModalB} />
来源:https://stackoverflow.com/questions/42033960/is-it-possible-to-match-the-part-of-a-route-in-react-router-4