繁体   English   中英

在 react 中用情感为 props 传递的组件设置样式

[英]Styling a component passed by props with emotion in react

我通过道具传递一个组件,例如:

const someicon = <SomeIcon>
..
<Sidebar icon={someicon} />

然后用情感/风格来设计它:

const StyledIcon = styled(props.icon)`
  ...
`;

但我得到的 StyledIcon 是 object:

{$$typeof: Symbol(react.forward_ref), defaultProps: undefined, __emotion_real: {…}, __emotion_base: {…}, render: ƒ, …}$$typeof: Symbol(react.forward_ref)defaultProps: undefinedrender: ƒ (props, ref)withComponent: ƒ (nextTag, nextOptions)__emotion_base: {$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}__emotion_forwardProp: undefined__emotion_real: {$$typeof: Symbol(react.forward_ref), defaultProps: undefined, __emotion_real: {…}, __emotion_base: {…}, render: ƒ, …}__emotion_styles: (4) ["label:StyledAppIcon;", "color:", ƒ, ";width:2em;height:2em;/*# sourceMappingURL=data:ap…1cblxuZXhwb3J0IGRlZmF1bHQgU2lkZWJhcjtcbiJdfQ== */"]displayName: (...)toString: ƒ value()get displayName: ƒ ()set displayName: ƒ (name)__proto__: Object

我无法弄清楚这里发生了什么以及如何通过道具正确传递组件,然后设置它们的样式然后渲染它们。

谢谢

这是因为styled-components仅适用于组件,因此您必须将图标作为组件传递(至少是返回 JSX 的 function):

const someicon = () => <SomeIcon>

此外,您必须转发className道具:

const someicon = ({ className }) => <SomeIcon className={className}>

如果您的图标组件包含的模板不超过<SomeIcon /> ,则无需包装它,只需编写以下代码:

<Sidebar icon={SomeIcon} />

并确保从 props 中正确检索到className并将其设置在SomeIcon组件内的 DOM 元素上,因为styled-components在后台与类一起使用。

注意:这实际上不是在另一个组件中声明样式组件的好习惯,因为它将在每个渲染周期中计算,并且会显示以下警告:

id 为“sc-iqAclL”的组件 Styled(icon) 已动态创建。 您可能会看到此警告,因为您在另一个组件中调用了 styled。 要解决此问题,只需在任何渲染方法和 function 组件之外创建新的 StyledComponents。

暂无
暂无

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

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