我试图实现你所说的。在“子路由”之间移动时,我可以阻止整页转换,但我无法触发子路由的特定转换(由于父路由重新渲染)。这是我想出的https://codesandbox.io/s/Dkwyg654k。
import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import { CSSTransitionGroup } from 'react-transition-group';
import About from './components/About';
import Home from './components/Home';
import Topics from './components/Topics';
import './styles.css';
var currentRoute = ''
const getParentPathname = pathname =>
pathname === '/'
? ''
: (/([a-zA-Z])([^/]*)/).exec(pathname)[0]
class BasicExample extends Component {
render = () =>
<Router>
<Route
render={({ location, history, match }) => {
const nextRoute = getParentPathname(location.pathname)
const isParentRouteChange =
!currentRoute.includes(nextRoute) ||
!nextRoute.includes(currentRoute)
currentRoute = nextRoute
return(
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<hr />
<CSSTransitionGroup
// transitionEnter={isParentRouteChange}
// transitionLeave={isParentRouteChange}
transitionEnterTimeout={500}
transitionLeaveTimeout={500}
transitionName={isParentRouteChange ? "fade" : "slide"}
>
<Switch key={location.key} location={location}>
<Route exact path="/" component={Home} location={location} key={location.key}/>
<Route path="/about" component={About} location={location} key={location.key}/>
<Route path="/topics" component={Topics} location={location} key={location.key}/>
</Switch>
</CSSTransitionGroup>
</div>
)
}
}/>
</Router>
}
render(<BasicExample />, document.body)