简体   繁体   English

创建包装组件并将其传递到React Router的推荐方法是什么?

[英]What's the recommended way to create and pass a wrapped component to React Router?

I have a bunch of routes, and I want to wrap the component that is rendered for each route in a styled div , but I'm trying to make the code DRYer. 我有一堆路线,我想将为每个路线呈现的组件包装在样式div ,但是我正在尝试编写代码DRYer。

How would you refactor this so that I can add n routes without repeating the <div> each time? 您将如何重构它,以便我可以添加n条路由而不必每次都重复<div>

<Route
   path="/"
   exact
   component={
     <div className={css(styles.fadeIn)}>
       <Home />
     </div>
    }
   />
<Route
 path="/about"
 exact
 component={
   <div className={css(styles.fadeIn)}>
     <About />
   </div>
  }
 />

You can compose the Route component pretty much the same as any other react component. 您可以将Route组件与其他任何react组件组成几乎相同。 You could do the following: 您可以执行以下操作:

const AnimatedRoute = ({ component: Component, ...rest}) => (
  <div className={css(styles.fadeIn)}>
    <Route component={Component} {...rest} />
  </div>
)

//Somewhere else
<AnimatedRoute component={About} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM