简体   繁体   中英

How to make a layout with Styled Components?

Since the point of React is to make components reusable, and the layout of a page can change drastically from one app to another, I'm not sure where to put my layout-specific styles. Any suggestions?

The placement of a component should be decided by the 'consumer' of the component. So, for example, if you have 3 components:

  • ComponentA
    • ComponentB
      • ComponentC

  • ComponentC would decide the placement all its sub-components.
  • ComponentB would decide the placement all its sub-components, which would include ComponentC
  • ComponentA would decide the placement all its sub-components, which would include ComponentB

If you mean global styles in React you have two options:

option 1 : throw them in as a regular CSS file - see how Create-React-App does it - or just add them to you index/html where you're rendering the app.

option 2: Styled Components has support for Theming, meaning they give you a <ThemeProvider /> element and then you can use the provided styles in any component downstream. Here are the docs including a basic example .

If on the other hand you're referring layouts but on a component / sub component level, you basically pull the layout styles as far up as you can. An example would be having a element with its own styles; something like this:

// Layout.js
const myStyledContainer = styled.div`
display: flex;
`
export default (props) => <myStyledContainer>{props.children}</myStyledContainer>

Then in you App.js you'd have something like:

return (
<Layout>

*... your other components or pages or whatever*
</Layout>

It's a matter of opinion so just try things and see what works for your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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