简体   繁体   English

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

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

I am passing a component via props like:我通过道具传递一个组件,例如:

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

Then styling it with emotion/styled like:然后用情感/风格来设计它:

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

But the StyledIcon I am getting is a object:但我得到的 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

I can't figure out what is going on here and how to properly pass components via props, then style them and then render them.我无法弄清楚这里发生了什么以及如何通过道具正确传递组件,然后设置它们的样式然后渲染它们。

Thanks谢谢

That's because styled-components only works for components so you have to pass the icon as a component (at least a function that returns JSX):这是因为styled-components仅适用于组件,因此您必须将图标作为组件传递(至少是返回 JSX 的 function):

const someicon = () => <SomeIcon>

Also, you have to forward the className prop:此外,您必须转发className道具:

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

If your icon component contains no more template than <SomeIcon /> , then no need to wrap it, simply write this:如果您的图标组件包含的模板不超过<SomeIcon /> ,则无需包装它,只需编写以下代码:

<Sidebar icon={SomeIcon} />

And make sure that the className is properly retrieved from the props and set on a DOM element inside the SomeIcon component, because styled-components works with classes under the hood.并确保从 props 中正确检索到className并将其设置在SomeIcon组件内的 DOM 元素上,因为styled-components在后台与类一起使用。

Note: this is actually not a good practice to declare a styled component inside another component as it will be computed on every render cycle, and will display this warning:注意:这实际上不是在另一个组件中声明样式组件的好习惯,因为它将在每个渲染周期中计算,并且会显示以下警告:

The component Styled(icon) with the id of "sc-iqAclL" has been created dynamically. id 为“sc-iqAclL”的组件 Styled(icon) 已动态创建。 You may see this warning because you've called styled inside another component.您可能会看到此警告,因为您在另一个组件中调用了 styled。 To resolve this only create new StyledComponents outside of any render method and function component.要解决此问题,只需在任何渲染方法和 function 组件之外创建新的 StyledComponents。

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

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