简体   繁体   中英

Loosing component props when using 'as' styled-component prop on an extended styled-component

I wrote a CallToAction component like so:

const CallToAction = ({ text = "Default text" }) => (
  <S_CallToAction>{text}</S_CallToAction>
)
const S_CallToAction = styled.div`
  // Some styles...
`
export default CallToAction

Then , when I want to use it in another components and overload it with some more styles, I'm loosing my "text" prop, and the previous styles I declared in my "CallToAction" component. This works well when I remove the "as={'button'}" prop.

Here is what I did when I wanted to use it in another component, overloading it:

import CallToAction from "components/common/callToAction"

...

        <S_ProductButton
          as={'button'}
          text={`I want my text to display and my style being inherited`}
        />

...

const S_ProductButton = styled(CallToAction)`
      width: 50%;
      margin: auto;
      min-width: 300px;
`

Can someone explain me why adding the "as" prop both makes my style overloading and my text prop don't work anymore? Also, how do you deal with this kind of situation?

Note : I'm new to styled components... I could export the "S_CallToAction" (styles only) and use it in my other components but is it a good solution? That would break the idea of "one component = one style" to me, which is the idea behind styled-components...

Ok, I finally found a solution to my issue ! There's another prop for my use case which is " forwardedAs " used like the "as" prop, and this makes my overloaded styled-component work as intended.

I had to spread all the props via {...props} on my CallToAction component (which is initially a styled.a)

const CallToAction = ({ text = "Text", href, ...props}) => (
  <S_CallToAction href={href ? href : null} {...props}>{text}</S_CallToAction>
)

And then on my extended component, I had to use forwardedAs:

           <S_ProductButton
              forwardedAs={'button'}
              text={`I have my text and my styles inherited`}
            /> 

Here are details about the issue I faced, and why styled-components acts like this: https://github.com/styled-components/styled-components/issues/1981

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