简体   繁体   English

尝试直接使用 styled-components 设置组件样式时出错

[英]Error trying to style a component directly with styled-components

I'm trying to style a component like this:我正在尝试设计这样的组件:

function _MenuItem({label, icon}){
    return <div>
        {icon}
        <p>{label}</p>
    </div>
}

export const MenuItem = styled(props => <_MenuItem {...props} />)`
    color: red;
    p{color: red}
    *{color: red}
`

The component is rendering, but the styles are not being applied.该组件正在呈现,但未应用 styles。

I have managed to apply the styles by making a styled div and creating the component from that div , but I was wondering if there is a way to apply the styles directly to the component?我已经通过制作样式化的div并从该div创建组件成功地应用了 styles,但我想知道是否有办法将 styles 直接应用到组件?

I am very new with react and more with styled-components so I assume that I have misunderstood some basic concepts.我对 react 很陌生,对 styled-components 更陌生,所以我认为我误解了一些基本概念。

Making a styled div is the correct way of doing things.制作样式化的 div 是正确的做事方式。 I couldn't find anything on styling a component directly nor felt the urge to done it before.我找不到任何关于直接设计组件样式的东西,也没有感觉到以前做过它的冲动。

Even when the styled-component docs describehow to style any component , they are basically styling an element just with a different syntax.即使当 styled-component 文档描述了如何设置任何组件的样式时,它们基本上只是使用不同的语法设置元素的样式。

There doesn't seem to be a good enough reason to do what you want to do, since you can achieve what you want to achieve by using the styled components as intended.似乎没有足够好的理由去做您想做的事,因为您可以通过按预期使用样式化组件来实现您想要实现的目标。

The following way of doing things works and it is super simple:以下做事方式有效,而且非常简单:

import styled from "styled-components"

const _MenuItem = ({label, icon}) => {
    return <Root>
        {icon}
        <p>{label}</p>
    </Root>
}

const Root = styled.div`
    color: red;
    p{color: red}
    *{color: red}
`

export default _MenuItem;

Please let me know if I'm missing some specific use-case or something other.如果我遗漏了一些特定的用例或其他东西,请告诉我。

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

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