[英]Styled-Component : I want to use Variable in Styled-Component
[英]Loosing component props when using 'as' styled-component prop on an extended styled-component
我写了一个 CallToAction 组件,如下所示:
const CallToAction = ({ text = "Default text" }) => (
<S_CallToAction>{text}</S_CallToAction>
)
const S_CallToAction = styled.div`
// Some styles...
`
export default CallToAction
然后,当我想在另一个组件中使用它并用更多的 styles 重载它时,我失去了我的“文本”道具,以及我在“CallToAction”组件中声明的之前的 styles。 当我删除 "as={'button'}" 道具时,这很有效。
这是我想在另一个组件中使用它时所做的,重载它:
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;
`
有人可以解释一下为什么添加“as”道具会使我的样式重载和我的文本道具不再起作用吗? 还有,遇到这种情况怎么处理?
注意:我是样式组件的新手...我可以导出“S_CallToAction”(仅限样式)并在我的其他组件中使用它,但这是一个好的解决方案吗? 这会打破我对“一个组件=一种样式”的想法,这是样式组件背后的想法......
好的,我终于找到了解决问题的方法! 对于我的用例,还有另一个道具是“ forwardedAs ”,就像“as”道具一样使用,这使得我的重载样式组件按预期工作。
我必须通过 {...props} 在我的 CallToAction 组件(最初是 styled.a)上传播所有道具
const CallToAction = ({ text = "Text", href, ...props}) => (
<S_CallToAction href={href ? href : null} {...props}>{text}</S_CallToAction>
)
然后在我的扩展组件上,我不得不使用 forwardedAs:
<S_ProductButton
forwardedAs={'button'}
text={`I have my text and my styles inherited`}
/>
以下是有关我面临的问题的详细信息,以及为什么 styled-components 会这样: https://github.com/styled-components/styled-components/issues/1981
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.