使用对象定义样式

使用对象来定义样式是Emotion与Styled Components不同的一点,对象可以使样式的定义更具有表现力,也便于Lint工具检查。使用对象来定义样式的时候,只需要将使用连词符-分隔单词的kebab-case样式属性改为camelCase形式书写即可。

例如以下就是一个使用对象来定义样式的示例。

import { jsx } from '@emotion/react'; function App() { return ( <div css={{ color: 'blue', backgroundColor: 'gray' }}> Some text. </div> ); }

对象样式也可以与styled结合使用,用于样式组件的定义。

import styled from '@emotion/styled'; const Button = styled.button( { color: 'darkorchid' }, props => ({ fontSize: props.fontSize }) ); function App() { return <Button fontSize={16}>Action!</Button>; }

在对象样式中可以直接书写数字,数字值一般都会采用px作为单位。对于类似于fontWeight之类的属性,数字将会自动选择其对应的单位。

有些样式属性是不被一些浏览器支持的,这时可以使用数组来定义回退值。例如以下示例。

function App() { return ( <div css={{ background: ['red', 'linear-gradient(#000, #fff)'], lineHeight: 30 }}> Some text. </div> ); }

借助于css函数,还可以把对象样式定义成可以在多个位置直接复用的形式,而且还可以支持样式的组合。具体使用可以参考以下示例。

import { jsx, css } from '@emotion/react'; const redText = css({ color: 'red' }); const redOnHover = css({ '&.hover,&.focus': redText }); const redTextOnBlack = css( { backgroundColor: 'black', color: 'green' }, redText ); function App() { return ( <div> <p css={redText}>Red text on white.</p> <button css={redOnHover}>Color changes on hover</button> <p css={redTextOnBlack}>Red Ttext on black.</p> </div> ); }