简体   繁体   中英

styled-components and custom styles?

I've been loving checking out styled-components, but getting a bit stuck with the concept of extracting everything out into a component, and how to tweak styles for a particular use case. For example:

<Flex>
   <MyStyledTitle>Hello I am a Title</MyStyledTitle>
   <MyStyledBodyText>blah</MyStyledBodyText>
</Flex>

Let's say that I wanted to make the following customisations for this use case:

  1. styled title grey (subdued text colour),
  2. the body text to have a right margin of 100px (don't ask why).

The styled-components way, the first part could be done like:

<MyStyledTitle colorTint='subdued' /> 

or even

<MyStyledTitle>
    <SubduedText>MyTitle</SubduedText>
</MyStyledTitle>

Perhaps using a prop for title that lets you configure it to use subdued text or ANOTHER hild component that defines the grey text..

But what about for the second option...

<MyStyledBodyText style={{paddingRight: 100}} /> 

Inline style? Use a Grid or layout component around it?

At which point does something become a specific styled-component and if not, then how does one customise smaller style changes?


While i really like this idea of removing the mapping between component + class name, I guess i'm feeling a bit torn between the classical idea of having a 'style sheet' file that can contain all the classes and modifier css, then using a presenter to choose between the combinations of css classes.

I might be missing something here, but just keen to see some bigger examples of styled components in practice. Any links / tips would be greatly appreciated!

We've been using styled-components in our project extensively. Few basic patterns/conventions we use are

  1. Components created using StyledComponents are not used across React Components. Under extreme scenarios, we pull them into external files and export.
  2. DIV is the most extensively used styled-component ( styled.div ). (Ofcourse we do use other html elements like button, table td etc., but styled explicitly).
  3. Different styles for the same HTML element (or) React Component are declared explicitly as different styles. (If you refer to FAQ section of the styled-components docs, you might notice these - https://github.com/styled-components/styled-components/blob/master/docs/faq.md )

Overall to answer your question, we have moved away from the classical stylesheet and as well thinking about combining multiple styles. It has worked well, except that looking up on unit tests is a bit painful.

Thanks

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