1

我开始用情感 js 学习 css-in-js。

有人可以告诉我两者之间是否真的有区别

const Component = Styled('div')`
  color: 'red'
`;

const Component = () => (
  <div className={css`color: red`}/>
)
  1. 它是样式化的某种帮助程序还是 CSS 的速记?
  2. 有什么建议什么时候使用吗?

看起来所有 Styled 都可以,可以用 css + cx 代替

4

1 回答 1

2

我认为主要区别在于css只生成具有一组特定 CSS 属性的选择器,而styled需要一个组件来附加样式(即div在您的示例中类似)。

如果你想用css你写的多个/不同的元素来设置样式

const specificStyle = css`
  color: red
`
<ComponentThatRendersADiv className={specificStyle} />
<ComponentThatRendersASpan className={specificStyle} />
<ComponentThatRendersAButton className={specificStyle} />

如果您想为某个组件设置样式styled并重用它:

const ComponentThatRendersADiv = styled('div')`
  color: red
`
const ComponentThatRendersASpan = ComponentThatRendersADiv.withComponent('span')
const ComponentThatRendersAButton = ComponentThatRendersADiv.withComponent('button')

<ComponentThatRendersADiv />
<ComponentThatRendersASpan />
<ComponentThatRendersAButton />

所以css感觉更像是编写 CSS 的典型方式,您可以创建应用于元素/组件的选择器。

styled创建一个特定的组合/组件。

文档styledhttps
://emotion.sh/docs/styled 文档csshttps ://emotion.sh/docs/css

于 2018-11-13T05:59:41.747 回答