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

javascript - Styled components API - withComponent vs. as - Stack Overflow

programmeradmin6浏览0评论

I've stumbled upon a question regarding the Styled Component API updates in version 4:

  • withComponent which was handy to use, is now deprecated
  • as is the introduced alternative to it

But as far as I understood as is meant to be used on a JSX template level whereas withComponent was used within a styled ponent declaration.

So what is the suggested workflow in situations like following:

const BaseComponent = styled.div`
  color: red;
`;

const HeadingComponent = BaseComponent.withComponent('h4');

assuming that we use <HeadingComponent /> in a lot of different places.

Would it mean that instead of having a second styled ponent, declare a React ponent using the <BaseComponent as="h4" /> and instead of reusing the styled ponent, reuse the React ponent?

So transfer usage of withComponent into creating a new React ponent using the base styled ponent with as attribute?

Thanks in advance,

Andreas

I've stumbled upon a question regarding the Styled Component API updates in version 4:

  • withComponent which was handy to use, is now deprecated
  • as is the introduced alternative to it

But as far as I understood as is meant to be used on a JSX template level whereas withComponent was used within a styled ponent declaration.

So what is the suggested workflow in situations like following:

const BaseComponent = styled.div`
  color: red;
`;

const HeadingComponent = BaseComponent.withComponent('h4');

assuming that we use <HeadingComponent /> in a lot of different places.

Would it mean that instead of having a second styled ponent, declare a React ponent using the <BaseComponent as="h4" /> and instead of reusing the styled ponent, reuse the React ponent?

So transfer usage of withComponent into creating a new React ponent using the base styled ponent with as attribute?

Thanks in advance,

Andreas

Share Improve this question asked Feb 4, 2019 at 10:44 andi1984andi1984 67610 silver badges28 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

While I personally prefer reusing the React ponent with the as prop, it could be easier for you to just refactor the usages into BaseComponent.attrs({ as: 'h4' })``.

Instead of doing this:

const Anchor = styled.a`color: hotpink;`
const Span = Anchor.withComponent('span')

do this:

const styles = css`color: hotpink;`

const Anchor = styled.a(styles)
const Span = styled.span(styles)

styled-ponents v6 removed withComponent, so I expect this question to get a lot more attention.

发布评论

评论列表(0)

  1. 暂无评论