Emotion项目中的css prop使用指南
什么是css prop
Emotion是一个流行的CSS-in-JS库,它提供了一种名为css prop
的核心功能,这是使用Emotion进行样式设计的主要方式。css prop
提供了一个简洁灵活的API来为组件添加样式。
两种配置方式
要在项目中使用css prop
,有两种主要的配置方法:
1. Babel预设配置(推荐)
这种方法需要在项目中配置Babel预设,适合可以自定义Babel配置的项目:
// .babelrc
{
"presets": ["@emotion/babel-preset-css-prop"]
}
对于使用React 16.14.0及以上版本的项目,可以启用新的JSX运行时:
{
"presets": [
[
"@babel/preset-react",
{ "runtime": "automatic", "importSource": "@emotion/react" }
]
],
"plugins": ["@emotion/babel-plugin"]
}
2. JSX编译指示(Pragma)方法
这种方法适合不能修改Babel配置的环境(如Create React App),通过在文件顶部添加特殊注释:
/** @jsx jsx */
import { jsx } from '@emotion/react'
对于使用新版JSX运行时的项目,可能需要使用:
/** @jsxImportSource @emotion/react */
使用css prop的两种样式写法
对象样式写法
可以直接传递样式对象给css prop
:
<div
css={{
backgroundColor: 'hotpink',
'&:hover': {
color: 'lightgreen'
}
}}
>
这个div有粉色背景
</div>
字符串样式写法
需要使用css
函数作为模板标签:
import { css } from '@emotion/react'
const color = 'darkgreen'
<div
css={css`
background-color: hotpink;
&:hover {
color: ${color};
}
`}
>
这个div有粉色背景
</div>
样式优先级规则
理解Emotion中的样式优先级非常重要:
- 通过
className
prop传递的Emotion样式会覆盖css prop
的样式 - 非Emotion生成的类名会被忽略,并附加到计算后的Emotion类名后面
这种优先级设计允许父组件通过className
prop来自定义子组件的样式。
样式组合示例
Emotion支持样式的组合继承:
const BaseText = props => (
<p
css={{
margin: 0,
fontSize: 12,
color: 'black'
}}
{...props}
/>
)
const ArticleText = props => (
<BaseText
css={{
fontSize: 14,
color: 'darkgray'
}}
{...props}
/>
)
const SmallArticleText = props => (
<ArticleText
css={{
fontSize: 10
}}
{...props}
/>
)
在这个例子中,样式会按照CSS的"出现顺序"规则进行合并,后面的属性会覆盖前面的同名属性。
注意事项
- 不要使用
@babel/plugin-transform-react-inline-elements
插件,它与css prop
不兼容 - 使用
React.cloneElement
时,如果克隆的元素原本没有css prop
,则难以添加新的样式
通过理解这些概念和规则,开发者可以充分利用Emotion的css prop
功能,创建灵活可维护的样式系统。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考