【问题标题】:Styling a component passed by props with emotion in react在 react 中用情感为 props 传递的组件设置样式
【发布时间】:2021-08-02 21:24:45
【问题描述】:

我通过以下道具传递一个组件:

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

然后用情感/样式设置它:

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 正确传递组件,然后设置样式,然后渲染它们。

谢谢

【问题讨论】:

  • 在 JSX 中写 StyledIcon 会发生什么?
  • 未处理的运行时错误错误:对象作为 React 子项无效(发现:具有键 {$$typeof、render、defaultProps、__emotion_real、__emotion_base、__emotion_styles、__emotion_forwardProp、withComponent} 的对象)。如果您打算渲染一组子项,请改用数组。
  • 顺便说一句,我发现通过像 这样的类名传递组件,然后在侧边栏组件中为此类应用样式也可以。现在只需要传递类,至少节省了重复的样式。

标签: javascript reactjs styled-components emotion


【解决方案1】:

那是因为styled-components 仅适用于组件,所以您必须将图标作为组件传递(至少是返回 JSX 的函数):

const someicon = () => <SomeIcon>

另外,你必须转发className prop:

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

如果您的图标组件包含的模板不超过&lt;SomeIcon /&gt;,则无需包装它,只需这样写:

<Sidebar icon={SomeIcon} />

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

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

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

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 2019-06-26
    • 2017-08-11
    • 2019-06-04
    • 2020-02-15
    • 2019-09-11
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多