导航菜单

  • 0.api
  • 0.Async
  • 0.module
  • 1.ES2015
  • 2.Promise
  • 3.Node
  • 4.NodeInstall
  • 5.REPL
  • 6.NodeCore
  • 7.module&NPM
  • 8.Encoding
  • 9.Buffer
  • 10.fs
  • 11.Stream-1
  • 11.Stream-2
  • 11.Stream-3
  • 11.Stream-4
  • 12-Network-2
  • 12.NetWork-3
  • 12.Network-1
  • 13.tcp
  • 14.http-1
  • 14.http-2
  • 15.compress
  • 16.crypto
  • 17.process
  • 18.yargs
  • 19.cache
  • 20.action
  • 21.https
  • 22.cookie
  • 23.session
  • 24.express-1
  • 24.express-2
  • 24.express-3
  • 24.express-4
  • 25.koa-1
  • 26.webpack-1-basic
  • 26.webpack-2-optimize
  • 26.webpack-3-file
  • 26.webpack-4.tapable
  • 26.webpack-5-AST
  • 26.webpack-6-sources
  • 26.webpack-7-loader
  • 26.webpack-8-plugin
  • 26.webpack-9-hand
  • 26.webpack-10-prepare
  • 28.redux
  • 28.redux-jwt-back
  • 28.redux-jwt-front
  • 29.mongodb-1
  • 29.mongodb-2
  • 29.mongodb-3
  • 29.mongodb-4
  • 29.mongodb-5
  • 29.mongodb-6
  • 30.cms-1-mysql
  • 30.cms-2-mysql
  • 30.cms-3-mysql
  • 30.cms-4-nunjucks
  • 30.cms-5-mock
  • 30.cms-6-egg
  • 30.cms-7-api
  • 30.cms-8-roadhog
  • 30.cms-9-yaml
  • 30.cms-10-umi
  • 30.cms-12-dva
  • 30.cms-13-dva-ant
  • 30.cms-14-front
  • 30.cms-15-deploy
  • 31.dva
  • 31.cms-13-dva-antdesign
  • 33.redis
  • 34.unittest
  • 35.jwt
  • 36.websocket-1
  • 36.websocket-2
  • 38.chat-api-1
  • 38.chat-api-2
  • 38.chat-3
  • 38.chat-api-3
  • 38.chat
  • 38.chat2
  • 38.chat2
  • 39.crawl-0
  • 39.crawl-1
  • 39.crawl-2
  • 40.deploy
  • 41.safe
  • 42.test
  • 43.nginx
  • 44.enzyme
  • 45.docker
  • 46.elastic
  • 47.oauth
  • 48.wxpay
  • index
  • 52.UML
  • 53.design
  • index
  • 54.linux
  • 57.ts
  • 56.react-ssr
  • 58.ts_react
  • 59.ketang
  • 59.ketang2
  • 61.1.devops-linux
  • 61.2.devops-vi
  • 61.3.devops-user
  • 61.4.devops-auth
  • 61.5.devops-shell
  • 61.6.devops-install
  • 61.7.devops-system
  • 61.8.devops-service
  • 61.9.devops-network
  • 61.10.devops-nginx
  • 61.11.devops-docker
  • 61.12.devops-jekins
  • 61.13.devops-groovy
  • 61.14.devops-php
  • 61.15.devops-java
  • 61.16.devops-node
  • 61.17.devops-k8s
  • 62.1.react-basic
  • 62.2.react-state
  • 62.3.react-high
  • 62.4.react-optimize
  • 62.5.react-hooks
  • 62.6.react-immutable
  • 62.7.react-mobx
  • 62.8.react-source
  • 63.1.redux
  • 63.2.redux-middleware
  • 63.3.redux-hooks
  • 63.4.redux-saga
  • 63.5.redux-saga-hand
  • 64.1.router
  • 64.2.router-connected
  • 65.1.typescript
  • 65.2.typescript
  • 65.3.typescript
  • 65.4.antd
  • 65.4.definition
  • 66-1.vue-base
  • 66-2.vue-component
  • 66-3.vue-cli3.0
  • 66-4.$message组件
  • 66-5.Form组件
  • 66-6.tree
  • 66-7.vue-router-apply
  • 66-8.axios-apply
  • 66-9.vuex-apply
  • 66-10.jwt-vue
  • 66-11.vue-ssr
  • 66-12.nuxt-apply
  • 66-13.pwa
  • 66-14.vue单元测试
  • 66-15.权限校验
  • 67-1-network
  • 68-2-wireshark
  • 7.npm2
  • 69-hooks
  • 70-deploy
  • 71-hmr
  • 72.deploy
  • 73.import
  • 74.mobile
  • 75.webpack-1.文件分析
  • 75.webpack-2.loader
  • 75.webpack-3.源码流程
  • 75.webpack-4.tapable
  • 75.webpack-5.prepare
  • 75.webpack-6.resolve
  • 75.webpack-7.loader
  • 75.webpack-8.module
  • 75.webpack-9.chunk
  • 75.webpack-10.asset
  • 75.webpack-11.实现
  • 76.react_optimize
  • 77.ts_ketang_back
  • 77.ts_ketang_front
  • 78.vue-domdiff
  • 79.grammar
  • 80.tree
  • 81.axios
  • 82.1.react
  • 82.2.react-high
  • 82.3.react-router
  • 82.4.redux
  • 82.5.redux_middleware
  • 82.6.connected
  • 82.7.saga
  • 82.8.dva
  • 82.8.dva-source
  • 82.9.roadhog
  • 82.10.umi
  • 82.11.antdesign
  • 82.12.ketang-front
  • 82.12.ketang-back
  • 83.upload
  • 84.graphql
  • 85.antpro
  • 86.1.uml
  • 86.2.design
  • 87.postcss
  • 88.react16-1
  • 89.nextjs
  • 90.react-test
  • 91.react-ts
  • 92.rbac
  • 93.tsnode
  • 94.1.JavaScript
  • 94.2.JavaScript
  • 94.3.MODULE
  • 94.4.EventLoop
  • 94.5.文件上传
  • 94.6.https
  • 94.7. nginx
  • 95.1. react
  • 95.2.react
  • 96.1.react16
  • 96.2.fiber
  • 96.3.fiber
  • 97.serverless
  • 98.websocket
  • 100.1.react-basic
  • 101.1.monitor
  • 101.2.monitor
  • 102.java
  • 103.1.webpack-usage
  • 103.2.webpack-bundle
  • 103.3.webpack-ast
  • 103.4.webpack-flow
  • 103.5.webpack-loader
  • 103.6.webpack-tapable
  • 103.7.webpack-plugin
  • 103.8.webpack-optimize1
  • 103.9.webpack-optimize2
  • 103.10.webpack-hand
  • 103.11.webpack-hmr
  • 103.11.webpack5
  • 103.13.splitChunks
  • 103.14.webpack-sourcemap
  • 103.15.webpack-compiler1
  • 103.15.webpack-compiler2
  • 103.16.rollup.1
  • 103.16.rollup.2
  • 103.16.rollup.3
  • 103.16.vite.basic
  • 103.16.vite.source
  • 103.16.vite.plugin
  • 103.16.vite.1
  • 103.16.vite.2
  • 103.17.polyfill
  • 104.1.binary
  • 104.2.binary
  • 105.skeleton
  • 106.1.react
  • 106.2.react_hooks
  • 106.3.react_router
  • 106.4.redux
  • 106.5.redux_middleware
  • 106.6.connected-react-router
  • 106.6.redux-first-history
  • 106.7.redux-saga
  • 106.8.dva
  • 106.9.umi
  • 106.10.ketang
  • 106.11.antdesign
  • 106.12.antpro
  • 106.13.router-6
  • 106.14.ssr
  • 106.15.nextjs
  • 106.16.1.cms
  • 106.16.2.cms
  • 106.16.3.cms
  • 106.16.4.cms
  • 106.16.mobx
  • 106.17.fomily
  • 107.fiber
  • 108.http
  • 109.1.webpack_usage
  • 109.2.webpack_source
  • 109.3.dll
  • 110.nest.js
  • 111.xstate
  • 112.Form
  • 113.redux-saga
  • 114.react+typescript
  • 115.immer
  • 116.pro5
  • 117.css-loader
  • 118.1.umi-core
  • 119.2.module-federation
  • 119.1.module-federation
  • 120.create-react-app
  • 121.react-scripts
  • 122.react-optimize
  • 123.jsx-runtime
  • 124.next.js
  • 125.1.linux
  • 125.2.linux-vi
  • 125.3.linux-user
  • 125.4.linux-auth
  • 125.5.linux-shell
  • 125.6.linux-install
  • 125.7.linux-system
  • 125.8.linux-service
  • 125.9.linux-network
  • 125.10.nginx
  • 125.11.docker
  • 125.12.ci
  • 125.13.k8s
  • 125.14.k8s
  • 125.15.k8s
  • 125.16.k8s
  • 126.11.react-1
  • 126.12.react-2
  • 126.12.react-3
  • 126.12.react-4
  • 126.12.react-5
  • 126.12.react-6
  • 126.12.react-7
  • 126.12.react-8
  • 127.frontend
  • 128.rollup
  • 129.px2rem-loader
  • 130.health
  • 131.hooks
  • 132.keepalive
  • 133.vue-cli
  • 134.react18
  • 134.2.react18
  • 134.3.react18
  • 135.function
  • 136.toolkit
  • 137.lerna
  • 138.create-vite
  • 139.cli
  • 140.antd
  • 141.react-dnd
  • 142.1.link
  • 143.1.gulp
  • 143.2.stream
  • 143.3.gulp
  • 144.1.closure
  • 144.2.v8
  • 144.3.gc
  • 145.react-router-v6
  • 146.browser
  • 147.lighthouse
  • 148.1.basic
  • 148.2.basic
  • 148.3.basic
  • 148.4.basic
  • 148.5.basic
  • 149.1.vite
  • 149.2.vite
  • 149.3.vite
  • 149.4.vite
  • 150.react-window
  • 151.react-query
  • 152.useRequest
  • 153.transition
  • 154.emotion
  • 155.1.formily
  • 155.2.formily
  • 155.3.formily
  • 155.3.1.mobx.usage
  • 155.3.2.mobx.source
  • 156.vue-loader
  • 103.11.mf
  • 157.1.react18
  • 158.umi4
  • 159.rxjs
  • 159.rxjs2
  • 160.bff
  • 161.zustand
  • 162.vscode
  • 163.emp
  • 164.cors
  • 1. CSS模块化方案
    • 1.1 CSS 命名方法
    • 1.2 CSS Modules
    • 1.3 CSS-in-JS
      • 1.3.1 案例
      • 1.3.2 CSS-IN-JS优缺点
      • 1.3.3 选型
  • 2. emotion
  • 3.@emotion/css
    • 3.1 模板字符串
      • 3.1.1 src\main.jsx
      • 3.1.2 src\App.jsx
      • 3.1.3 css\index.js
      • 3.1.4 css.js
      • 3.1.5 serialize\index.jsx
      • 3.1.6 serializeStyles.jsx
      • 3.1.7 utils\index.jsx
      • 3.1.8 hashString.jsx
      • 3.1.9 insertStyles.jsx
    • 3.2 对象
      • 3.2.1 src\App.jsx
      • 3.2.2 serializeStyles.jsx
  • 4.@emotion/react
    • 4.1 vite.config.js
    • 4.2 src\App.jsx
    • 4.3 react\index.jsx
    • 4.4 css.jsx
    • 4.5 jsx.jsx
    • 4.6 serializeStyles.jsx
    • 4.7 Insertion.jsx
    • 4.8 utils\index.jsx
  • 5. @emotion/styled
    • 5.1 src\App.jsx
    • 5.2 styled\index.jsx
  • 6. 根据props属性覆盖样式
    • 6.1 src\App.jsx
    • 6.2 styled\index.jsx
    • 6.3 serializeStyles.jsx
  • 7. 为组件添加样式
    • 7.1 src\App.jsx
  • 8. 父组件设置子组件
    • 8.1 vite.config.js
    • 8.2 src\App.jsx
  • 9. 嵌套选择器
    • 9.1 src\App.jsx
  • 10. as属性
    • 10.1 src\App.jsx
  • 11.组合样式
    • 11.1 src\App.jsx
  • 12.全局样式
    • 12.1 src\App.jsx
  • 13.关键帧动画
    • 13.1 src\App.jsx
  • 14.模板字符串

1. CSS模块化方案 #

1.1 CSS 命名方法 #

  • 通过人工的方式来约定命名规则
  • BEM是一种典型的 CSS 命名方法论,BEM的命名规矩就是block-name__element-name--modifier-name,也就是模块名 + 元素名 + 修饰器名
  • OOCSS(Object-Oriented CSS)即面向对象的 CSS,它借鉴了 OOP(面向对象编程)的抽象思维,主张将元素的样式抽象成多个独立的小型样式类,来提高样式的灵活性和可重用性。
  • ITCSS(Inverted Triangle CSS,倒三角 CSS)是一套方便扩展和管理的 CSS 体系架构,它兼容 BEM、OOCSS、SMACSS 等 CSS 命名方法论
  • SMACSS即可伸缩及模块化的 CSS 结构

1.2 CSS Modules #

  • CSS Modules:一个 CSS 文件就是一个独立的模块,核心思想是 通过组件名的唯一性来保证选择器的唯一性,从而保证样式不会污染到组件外
  • CSS Modules允许我们像 import 一个 JS Module 一样去 import 一个 CSS Module.每一个 CSS 文件都是一个独立的模块,每一个类名都是该模块所导出对象的一个属性。通过这种方式,便可在使用时明确指定所引用的 CSS 样式。并且,CSS Modules 在打包时会自动将 id 和 class 混淆成全局唯一的 hash 值,从而避免发生命名冲突问题。
  • 使用 CSS Modules 时,推荐配合 CSS 预处理器(Sass/Less/Stylus)一起使用
  • CSS 预处理器提供了许多有用的功能,如嵌套、变量、mixins、functions 等,同时也让定义本地名称或全局名称变得容易

1.3 CSS-in-JS #

  • React 的出现,打破了以前关注点分离的网页开发原则,因其采用组件结构,而组件又强制要求将 HTML、CSS 和 JS 代码写在一起。表面上看是技术的倒退,实际上并不是
  • React 是在 JS 中实现了对 HTML 和 CSS 的封装,赋予了 HTML 和 CSS 全新的编程能力。对于 HTML,衍生了 JSX 这种 JS 的语法扩展,你可以将其理解为 HTML-in-JS;对于 CSS,衍生出一系列的第三方库,用来加强在 JS 中操作 CSS 的能力,它们被称为 CSS-in-JS
  • 随着 React 的流行以及组件化开发模式的深入人心,这种关注点混合的新写法逐渐成为主流
  • 实现
    • styled-components 36.7K
    • emotion 15K

1.3.1 案例 #

  • material-ui世界上最受欢迎的 React UI 框架

1.3.2 CSS-IN-JS优缺点 #

  • 优点
  • Scoping Styles 可以让CSS拥有独立的作用域,实现局部样式,防止样式冲突和影响组件外的内容
  • Dead Code Elimination 避免无用的CSS样式堆积
  • Critical CSS 重要的CSS放在头部的style标签内,其它的CSS异步加载可以减少渲染阻塞
  • State-based styling 根据组件的状态动态地生成样式
  • 更彻底的封装 让组件拥有更好的移植性和重用性
  • 缺点
  • Steep learning curve 陡峭的学习曲线
  • Runtime cost 运行时消耗
  • Unreadable class names 代码可读性差
  • No interoperability没有统一的 业界标准

1.3.3 选型 #

  • 我们一定要根据自己的实际情况进行衡量和取舍来确定是不是要在自己的项目中使用它
    • 前端初学者、页面功能简单、重视代码可读性和可维护性不要选择
    • 如果经验丰富、应用交互逻辑复杂、重视封装性和可移植性可以尝试

2. emotion #

  • emotion是一个用JS编写CSS样式的库
  • emotion是新一代的CSS-IN-JS解决方案
  • CSS-in-JS实现是通过生成唯一的CSS选择器来达到CSS局部作用域的效果

3.@emotion/css #

  • @emotion/css与框架无关,是使用 Emotion 的最简单方法
  • 不需要额外的设置、babel插件或其他配置更改
  • 支持自动供应商前缀、嵌套选择器和媒体查询

3.1 模板字符串 #

3.1.1 src\main.jsx #

src\main.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(
  <App />,
  document.getElementById('root')
)

3.1.2 src\App.jsx #

src\App.jsx

import { css } from './@emotion/css'
const className = css`
 color: red;
`;
function App() {
  return (
    <div className={className}>
      App
    </div>
  )
}
export default App

3.1.3 css\index.js #

src\@emotion\css\index.js

export { default as css } from './css';

3.1.4 css.js #

src\@emotion\css\css.js

import { serializeStyles } from '../serialize';
import { insertStyles } from '../utils';
function css(...args) {
  const serialized = serializeStyles(args);
  insertStyles(serialized);
  return 'css' + "-" + serialized.name;
}
export default css; 

3.1.5 serialize\index.jsx #

src\@emotion\serialize\index.jsx

export { default as serializeStyles } from './serializeStyles';

3.1.6 serializeStyles.jsx #

src\@emotion\serialize\serializeStyles.jsx

import { hashString } from '../utils';
function serializeStyles(args) {
  let styles = '';
  const strings = args[0];
  styles += strings[0];
  const name = hashString(styles);
  return { name, styles }
}
export default serializeStyles;

3.1.7 utils\index.jsx #

src\@emotion\utils\index.jsx

export { default as insertStyles } from './insertStyles'
export { default as hashString } from './hashString';

3.1.8 hashString.jsx #

src\@emotion\utils\hashString.jsx

function hashString(keys) {
  let val = 10000000;
  for (let i = 0; i < keys.length; i++) {
    val += keys.charCodeAt(i);
  }
  return val.toString(16).slice(0, 6);
}
export default hashString;

3.1.9 insertStyles.jsx #

src\@emotion\utils\insertStyles.jsx

function insertStyles(serialized) {
  const className = 'css' + "-" + serialized.name;
  const rule = "." + className + "{" + serialized.styles + "}";
  const tag = document.createElement('style');
  tag.setAttribute('data-emotion', 'css');
  tag.appendChild(document.createTextNode(rule));
  document.head.appendChild(tag);
}
export default insertStyles;

3.2 对象 #

3.2.1 src\App.jsx #

src\App.jsx

import { css } from './@emotion/css'
+const className = css(
+  {
+    color: 'red'
+  }
+);
function App() {
  return (
    <div className={className}>
      App
    </div>
  )
}
export default App

3.2.2 serializeStyles.jsx #

src\@emotion\serialize\serializeStyles.jsx

import { hashString } from '../utils';
function serializeStyles(args) {
  var styles = '';
  var strings = args[0];
+ if (strings.raw === undefined) {
+   styles += handleInterpolation(strings);
+ } else {
+   styles += strings[0];
+ }
  var name = hashString(styles);
  return { name, styles }
}

+function handleInterpolation(interpolation) {
+  switch (typeof interpolation) {
+    case 'object': {
+      return createStringFromObject(interpolation);
+    }
+  }
+}
+function createStringFromObject(obj) {
+  var string = '';
+  for (var key in obj) {
+    var value = obj[key];
+    string += key + ":" + value + ";";
+  }
+  return string;
+}
export default serializeStyles;

4.@emotion/react #

  • @emotion/react包需要React
  • 最好将React与可配置的构建环境一起使用
  • css属性支持
    • 类似于style prop,但也支持自动供应商前缀、嵌套选择器和媒体查询
npm install @emotion/react --save
  • pragma(注解) and pragmaFrag cannot be set when runtime is automatic.

4.1 vite.config.js #

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
  plugins: [react(
    {
+     jsxRuntime: 'classic'
    }
  )]
})

4.2 src\App.jsx #

src\App.jsx

+/** @jsx jsx */
+import { css, jsx } from './@emotion/react'
+const styles = css(
+  {
+    color: 'red'
+  }
+);
function App() {
  return (
+   <div css={styles}>
      App
    </div>
  )
}
export default App

4.3 react\index.jsx #

src\@emotion\react\index.jsx

export { default as css } from './css';
export { default as jsx } from './jsx';

4.4 css.jsx #

src\@emotion\react\css.jsx

import { serializeStyles } from '../serialize';
function css(...args) {
  return serializeStyles(args);
}
export default css; 

4.5 jsx.jsx #

src\@emotion\react\jsx.jsx

import { serializeStyles } from '../serialize';
import { Insertion } from '../utils';
function Emotion(props) {
  const serialized = serializeStyles(props.css);
  const { css, ...newProps } = props
  newProps.className = 'css' + "-" + serialized.name;
  const WrappedComponent = props.type;
  return (
    <>
      <Insertion serialized={serialized} />
      <WrappedComponent {...newProps} />
    </>
  )
}

function jsx(type, props, ...children) {
  return (
    <Emotion {...props} type={type}>
      {children}
    </Emotion >
  )
}
export default jsx;

4.6 serializeStyles.jsx #

src\@emotion\serialize\serializeStyles.jsx

import { hashString } from '../utils';
function serializeStyles(args) {
+  if (typeof args === 'object' && args.styles !== undefined) {
+    return args;
+  }
  var styles = '';
  var strings = args[0];
  if (strings == null || strings.raw === undefined) {
    styles += handleInterpolation(strings);
  } else {
    styles += strings[0];
  }
  var name = hashString(styles);
  return { name, styles }
}

function handleInterpolation(interpolation) {
  switch (typeof interpolation) {
    case 'object': {
      return createStringFromObject(interpolation);
    }
  }
}
function createStringFromObject(obj) {
  var string = '';
  for (var key in obj) {
    var value = obj[key];
    string += key + ":" + value + ";";
  }
  return string;
}
export default serializeStyles;

4.7 Insertion.jsx #

src\@emotion\utils\Insertion.jsx

import { useLayoutEffect } from 'react';
import insertStyles from './insertStyles';
function Insertion({ serialized }) {
  useLayoutEffect(() => {
    insertStyles(serialized);
  });
  return null;
};
export default Insertion;

4.8 utils\index.jsx #

src\@emotion\utils\index.jsx

export { default as insertStyles } from './insertStyles';
export { default as hashString } from './hashString';
+export { default as Insertion } from './Insertion';

5. @emotion/styled #

  • styled是一种创建附加样式的React组件的方法
npm install @emotion/styled --save

5.1 src\App.jsx #

src\App.jsx

+import styled from './@emotion/styled'
+const Button = styled.button(
  {
    color: 'red'
  }
+);
function App() {
  return (
+   <Button>Button</Button>
  )
}
export default App

5.2 styled\index.jsx #

src\@emotion\styled\index.jsx

import { serializeStyles } from '../serialize';
import { Insertion } from '../utils';
function createStyled(tag) {
  return function (...args) {
    function Styled(props) {
      const serialized = serializeStyles(args);
      const className = 'css' + "-" + serialized.name;
      const newProps = { ...props };
      newProps.className = className;
      const FinalTag = tag;
      return (
        <>
          <Insertion serialized={serialized} />
          <FinalTag {...newProps} />
        </>
      )
    }
    return Styled;
  }
}
const newStyled = createStyled.bind();
const tags = ['button', 'div'];
tags.forEach(function (tagName) {
  newStyled[tagName] = newStyled(tagName);
});
export default newStyled;

6. 根据props属性覆盖样式 #

6.1 src\App.jsx #

src\App.jsx

import styled from './@emotion/styled'
const Button = styled.button(
  {
    background: 'green',
    color: 'red'
+ }, props => ({
+   color: props.color
+ })
);
function App() {
  return (
+   <Button color="white">Button</Button>
  )
}
export default App

6.2 styled\index.jsx #

src\@emotion\styled\index.jsx

import { serializeStyles } from '../serialize';
import { Insertion } from '../utils';
function createStyled(tag) {
  return function (...args) {
    function Styled(props) {
+     const serialized = serializeStyles(args, props);
      const className = 'css' + "-" + serialized.name;
      const newProps = { ...props };
      newProps.className = className;
      const FinalTag = tag;
      return (
        <>
          <Insertion serialized={serialized} />
          <FinalTag {...newProps} />
        </>
      )
    }
    return Styled;
  }
}
const newStyled = createStyled.bind();
const tags = ['button', 'div'];
tags.forEach(function (tagName) {
  newStyled[tagName] = newStyled(tagName);
});
export default newStyled;

6.3 serializeStyles.jsx #

src\@emotion\serialize\serializeStyles.jsx

import { hashString } from '../utils';
+function serializeStyles(args, props) {
  if (typeof args === 'object' && args.styles !== undefined) {
    return args;
  }
  var styles = '';
  var strings = args[0];
  if (strings.raw === undefined) {
+   styles += handleInterpolation(props, strings);
  } else {
    styles += strings[0];
  }
  for (var i = 1; i < args.length; i++) {
    styles += handleInterpolation(props, args[i]);
  }
  var name = hashString(styles);
  return { name, styles }
}

+function handleInterpolation(props, interpolation) {
  switch (typeof interpolation) {
    case 'object': {
+     return createStringFromObject(props, interpolation);
    }
+   case 'function': {
+     if (props !== undefined) {
+       var result = interpolation(props);
+       return handleInterpolation(props, result);
+     }
+   }
  }
}
function createStringFromObject(obj) {
  var string = '';
  for (var key in obj) {
    var value = obj[key];
    string += key + ":" + value + ";";
  }
  return string;
}
export default serializeStyles;

7. 为组件添加样式 #

7.1 src\App.jsx #

src\App.jsx

import styled from './@emotion/styled'
+function Hello({ className }) {
+  return <button className={className}>Hello</button>
+}
+const RedHello = styled(Hello)`
+  color:red;
+`
function App() {
  return (
+   <RedHello>Button</RedHello>
  )
}
export default App;

8. 父组件设置子组件 #

.css-1wvgi8y-Parent{background:green;}
.css-10c6c3i-Child{color:red;}
.css-1wvgi8y-Parent .eesff8e1{color:blue;}
<div class="css-1wvgi8y-Parent eesff8e0">
  <div class="css-10c6c3i-Child eesff8e1">App</div>
</div>

8.1 vite.config.js #

npm install @emotion/babel-plugin --save

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
  plugins: [react(
    {
      jsxRuntime: 'classic',
      babel: {
+       plugins: ['@emotion/babel-plugin']
      }
    }
  )]
})

8.2 src\App.jsx #

src\App.jsx

import styled from '@emotion/styled'
const Child = styled.div({
  color: 'red'
})
const Parent = styled.div({
  background: 'green',
  [Child]: {
    color: 'blue'
  }
})
function App() {
  return (
    <>
      <Parent>
        <Child>Child</Child>
      </Parent>
      <Child>Child</Child>
    </>
  )
}
export default App

9. 嵌套选择器 #

9.1 src\App.jsx #

src\App.jsx

import styled from '@emotion/styled'
const Container = styled.div`
  width:200px;
  height:200px;
  background:lightgray;
  &:hover{
    background:pink;
  }
  & > p {
    color:green;
  }
`
function App() {
  return (
    <Container>
      Container
      <p>span</p>
    </Container>
  )
}
export default App

10. as属性 #

  • 要使用组件内的样式,但要更改呈现的元素,可以使用as属性

10.1 src\App.jsx #

src\App.jsx

import styled from '@emotion/styled'
const Button = styled.button`
 color:red
`

function App() {
  return (
    <Button as="a">
      Button
    </Button>
  )
}
export default App

11.组合样式 #

  • 要使用组件内的样式,但要更改呈现的元素,可以使用as属性

11.1 src\App.jsx #

src\App.jsx

/** @jsx jsx */
import { jsx, css } from '@emotion/react'
const base = css`
  color:white;
`
const warning = css`
  background:orange;
`
function App() {
  return (
    <button css={[base, warning]}>Button</button>
  )
}
export default App

12.全局样式 #

12.1 src\App.jsx #

src\App.jsx

/** @jsx jsx */
import { jsx, css, Global } from '@emotion/react'
const reset = css`
  body{
    margin:0;
  }
  a{
    color:red;
  }
`
function App() {
  return (
    <>
      <Global styles={reset} />
      <a>我是a标记</a>
    </>
  )
}
export default App

13.关键帧动画 #

13.1 src\App.jsx #

src\App.jsx

/** @jsx jsx */
import { jsx, css, keyframes } from '@emotion/react'

const bounce = keyframes`
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(100px);
  }
`
const base = css`
  width:100px;
  height:100px;
  background: green;
  position: absolute;
  animation: ${bounce} 1s ease infinite alternate;
`;
function App() {
  return (
    <div css={[base]}>
      文本
    </div>
  )
}
export default App

14.模板字符串 #

  • 模板字符串可以紧跟在一个函数名后面,该函数将被调用来处理这个模板字符串。这被称为标签模板功能
  • 标签模板其实不是模板,而是函数调用的一种特殊形式
  • 标签指的就是函数,紧跟在后面的模板字符串就是它的参数
  • 如果模板字符里面有变量,就不是简单的调用了,而是会将模板字符串先处理成多个参数,再调用函数
  • 模板处理函数的第一个参数(模板字符串数组),还有一个raw属性,保存的是转义后的原字符串
function tag(stringArr, ...values) {
  console.log(stringArr.raw);
  let output = "";
  let index;
  for (index = 0; index < values.length; index++) {
    output += stringArr[index] + values[index];
  }
  output += stringArr[index]
  return output;
}
let v1 = 1;
let v2 = 2;

let result = tag`a${v1}b${v2}c`;
console.log(result);

访问验证

请输入访问令牌

Token不正确,请重新输入