【问题标题】:Error trying to style a component directly with styled-components尝试使用 styled-components 直接设置组件样式时出错
【发布时间】:2022-02-12 00:16:18
【问题描述】:

我正在尝试像这样设置组件的样式:

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}
`

组件正在渲染,但未应用样式。

我已经设法通过创建样式 div 并从该 div 创建组件来应用样式,但我想知道是否有办法将样式直接应用到组件?

我对 react 和 styled-components 比较陌生,所以我认为我误解了一些基本概念。

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    制作样式化的 div 是正确的做事方式。我找不到任何关于直接为组件设置样式的内容,也没有以前做过的冲动。

    即使 styled-component 文档描述了 how to style any component,它们基本上只是用不同的语法设置元素的样式。

    似乎没有足够的理由去做你想做的事,因为你可以通过使用样式化的组件来达到你想要的效果。

    下面的做事方式很有效,而且超级简单:

    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;
    

    如果我缺少某些特定用例或其他内容,请告诉我。

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2021-11-04
      • 2018-11-12
      • 2020-08-18
      • 2020-04-04
      • 2020-05-01
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多