0

出于好奇,我在我的 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'};
`)`;

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

4

1 回答 1

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>
于 2019-01-07T22:31:41.920 回答