在反应中用情感对道具传递的组件进行样式化

Styling a component passed by props with emotion in react

我正在通过 props 传递组件,例如:

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

然后使用 emotion/styled 设计样式,例如:

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

但是我得到的 StyledIcon 是一个对象:

{$$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

我不知道这里发生了什么,也不知道如何通过 props 正确地传递组件,然后设置它们的样式然后渲染它们。

谢谢

那是因为 styled-components 只适用于 组件 所以你必须将图标作为组件传递(至少是 returns JSX 的功能):

const someicon = () => <SomeIcon>

还有,你要转发className prop:

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

如果你的图标组件包含的模板不超过<SomeIcon />,那么不需要包装它,只需这样写:

<Sidebar icon={SomeIcon} />

并确保 className 从道具中正确检索并设置在 SomeIcon 组件内的 DOM 元素上,因为 styled-components 与 类 引擎盖下。

注意:在另一个组件中声明样式化组件实际上不是一个好习惯,因为它会在每个渲染周期进行计算,并会显示此警告:

The component Styled(icon) with the id of "sc-iqAclL" has been created dynamically. You may see this warning because you've called styled inside another component. To resolve this only create new StyledComponents outside of any render method and function component.