day7: CSS style 规划 - CSS in JS(emotion 使用 - 1)

在上一篇我们介绍的 CSS in JS, 那这次我们来使用 CSS in JS 的框架 emotion, 目前 css in js 主流的框架大概有 css module, styled-component 和 emotion 这三套,这边因为作者本人平常习惯使用 emotion css, 所以直接用这套来使用。

安装

这里的范例皆使用 create react app 来示范

  1. 使用 emotion 的 CSS, classname 作法
npm install --save @emotion/css
import { css, cx } from '@emotion/css'

const color = 'red'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
			color:${color};
    `}
  >
    Demo
  </div>
)

使用这个做法,emotion 会使用 css 将 css 转成一个具有 hash 的随机 className ex: css-2342342 ,也可以将 `css``` 的内容变成一个变数,方便管理 css

import { css, cx } from '@emotion/css'

const color = 'red'

const rootStyle = css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
			color:${color};
    `

render(
  <div
    className={rootStyle}
  >
    Demo
  </div>
)

另外在 emotion className 底下的 css, 也可以像是一般 scss 一样, 可以嵌套指向子层,或是用 & 同一个 element 的不同状态的 className。注意这边要经由状态增加或减少 clssName 时,可以用 emotion 提供的 cx, 去帮助 className 的增加或减少。

import {useState} from 'react'
import { css, cx } from '@emotion/css'

const [isActive,setIsActive] = useState(true)

const color = 'red'

const rootStyle = css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
			color:${color};
			&.active{
				color:blue;
			}
			.text{
				color:black;
				font-size:12px;
			}
    `

render(
  <div
    className={cx(rootStyle,isActive && '.active')}
  >
		thie is demo.
    <p className="text" >hello</p>
  </div>
)

如果要使用 globalCSS 的话也可以使用 injectGlobal ,这个 emotion 内建语法, 这样全部的 element 都可以吃到这些 style

import {useState} from 'react'
import { injectGlobal } from '@emotion/css'

injectGlobal`
	* {
		box-sizing:border-box;
  }
  font-family: 'Robot';
`

https://emotion.sh/docs/install


<<:  【Day 08】 实作 - 透过 AWS 服务 - AppFlow 把 Google Analytics 资料存放至 AWS 中 ( 1 )

>>:  JavaScript学习日记 : Day10 - This

Day 13: 人工神经网路初探 激活函数(上)

激活函数 Activation Function 数学方法去决定neuron输出叫做激活函数(act...

[Android Studio 30天自我挑战] 练习APP-计算BMI

熟悉版面後,透过基本的原件就可以练习计算BMI的APP了 首先,在xml档新增标题及输入元件(Tex...

【Day28】this - call, apply, bind 与严谨模式

call, apply, bind 方法 当我们对函式使用 call, apply, bind 这三...

Day 2. Hashicorp Nomad: Upgrade

Hashicorp Nomad: Upgrade 升级方式: 现有主机更新binary档: 通常会建...

Day15 - 守护你的状态转移 : Guard

我们目前所学到的状态机已知,我们能透过 transition 限制状态转换的路径 对的 state ...