解决方案最终有点棘手
最后,我不得不创建一个新组件(抽屉)来处理动画。然后,将子路由添加到<Switch>
并将其指向父组件,如下所示:
应用程序.jsx
<Switch>
<Route exact path="/" component={Home} />
<Route path="/projects/:slug" component={Projects} />
<Route path="/projects" component={Projects} />
<Route component={NotFound} />
</Switch>
这意味着无论我点击/projects
或/projects/foo
,都会加载相同的 Projects 组件。
然后,在我的 Projects 组件中,我根据 slug 的存在有条件地渲染单个 Project 组件。我在我创建的处理动画的 Drawer 组件中执行此操作(使用这种方法,react-transition-group
不再需要,我通过 CSS 根据 Drawer 是否打开来制作动画)
项目.jsx
render() {
const renderProject = !!this.props.match.slug;
return (
<div className="projects">
[projects content here]
<Drawer isOpen={renderProject}>
<Project />
</Drawer>
<div>
)
};
这允许 slugged 路由存在于父路由中,同时在 slug 出现时仍由 Drawer 组件设置动画。
最后,我使用withRouter
提供的 HOCreact-router-dom
来包装导出的<Project>
组件,以便它可以完全利用路由器。
项目.jsx
export default withRouter(Project);