最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the best way to add conditional style with styled-components & styled-system? - Stack Overflow

programmeradmin5浏览0评论

I am trying to create a button ponent with styled-system and styled-ponents.

The variants of styled-system works great, but I am wondering how to add conditional css. For example, I am trying to render primary block button.

const StyledButton = styled(Button)`
  ${props => props.block && css`width: 100%;`
`;

// primary
<StyledButton block variant="primary" />

This works as expected, but I would like to know if there is any better way to apply block in beautiful way with pure javascript.

I am trying to create a button ponent with styled-system and styled-ponents.

The variants of styled-system works great, but I am wondering how to add conditional css. For example, I am trying to render primary block button.

const StyledButton = styled(Button)`
  ${props => props.block && css`width: 100%;`
`;

// primary
<StyledButton block variant="primary" />

This works as expected, but I would like to know if there is any better way to apply block in beautiful way with pure javascript.

Share Improve this question edited Apr 1, 2019 at 22:18 emil asked Apr 1, 2019 at 21:57 emilemil 6,3644 gold badges32 silver badges38 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

I think you can shorten your specific example as follows (you don't need to use css method there):

const StyledButton = styled(Button)`
  ${({block}) => block && 'width: 100%;'}
`;

But generally, I believe this is the only way of doing it. Doesn't really look ugly to me, but if you have some plex conditions you can probably move some code into separate variables or functions with descriptive names.

You can create a mixin and add it conditionally. You just need to import css from Styled-ponents. For example:

const buttonWidthMixin = css`
   width: 100%
`

Then you can add it to the button like so:

const StyledButton = styled(Button)`
   ${props => props.block && buttonWidthMixin};
`

Now if you add block prop to the button it will add our new mixin to css.

It is possible to return styles as json object this way:

const StyledButton = styled(Button)`
  ${({block}) => block && {width: '100%'}}
`;

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论