简体   繁体   English

在扩展样式组件上使用“as”样式组件道具时丢失组件道具

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

I wrote a CallToAction component like so:我写了一个 CallToAction 组件,如下所示:

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.然后,当我想在另一个组件中使用它并用更多的 styles 重载它时,我失去了我的“文本”道具,以及我在“CallToAction”组件中声明的之前的 styles。 This works well when I remove the "as={'button'}" prop.当我删除 "as={'button'}" 道具时,这很有效。

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?有人可以解释一下为什么添加“as”道具会使我的样式重载和我的文本道具不再起作用吗? 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?注意我是样式组件的新手...我可以导出“S_CallToAction”(仅限样式)并在我的其他组件中使用它,但这是一个好的解决方案吗? 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.对于我的用例,还有另一个道具是“ forwardedAs ”,就像“as”道具一样使用,这使得我的重载样式组件按预期工作。

I had to spread all the props via {...props} on my CallToAction component (which is initially a styled.a)我必须通过 {...props} 在我的 CallToAction 组件(最初是 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:然后在我的扩展组件上,我不得不使用 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以下是有关我面临的问题的详细信息,以及为什么 styled-components 会这样: https://github.com/styled-components/styled-components/issues/1981

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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