【问题标题】:Themed styled components combine props and theme主题风格的组件结合了道具和主题
【发布时间】:2019-05-31 03:41:19
【问题描述】:

出于好奇,我在我的 React 应用程序中使用样式化组件,并在其中使用建议的主题来让所有颜色和大小都可用。

目前我正在这样做:

export const TestComponent = styled.div`
    color: ${({ theme }) => theme.white};
    background-color: ${({ theme }) => theme.white};
    border: 1px solid ${({ theme }) => theme.white};
    display: ${({ check }) => check ? 'block' : 'none'};
`;

所以我正在使用来自ThemeProvider 的主题,并且还额外检查了外部组件。

我现在的问题是,为什么不能这样使用:

export const TestComponent = styled.div`${({ theme, check }) => (css`
    color: ${theme.white};
    background-color: ${theme.white};
    border: 1px solid ${theme.white};
    display: ${check ? 'block' : 'none'};
`)`;

岂不是更方便、更容易使用?如果是这样,他们为什么不这样建议呢?我只是害怕它有一些我现在看不到的巨大缺点。

【问题讨论】:

    标签: css reactjs sass styled-components emotion


    【解决方案1】:

    我认为这两种方法都没有问题。我已经在一个大型 React 应用程序中大量使用了你在第一个示例中所做的事情,并且没有任何问题(目前)。

    话虽如此,你的第二个例子是完全有效的。你甚至不需要css 助手:

    const Test = styled.div`
      ${({ theme }) => `color: ${theme.white};`}
    `;
    

    一般来说,我使用 css 帮助器来创建抽象/可共享的 css 块:

    const fontSize = css`
      font-size: ${({ small, large, theme }) => {
        if (small) return `${theme.small}rem`;
        if (large) return `${theme.large}rem`;
        return `${theme.normal}rem`;
      }};
    `;
    
    
    const Test = styled.div`
      ${({ theme }) => `color: ${theme.white};`}
      ${fontSize}
    `;
    

    然后:

    <Test small>Hello World</Test>
    

    【讨论】:

    • css 帮助器更像是我的 IDE 识别这些样式而不仅仅是字符串的帮助器。不过谢谢!我会尝试一下,希望没有问题!
    猜你喜欢
    • 1970-01-01
    • 2016-06-05
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 2020-01-19
    • 1970-01-01
    相关资源
    最近更新 更多