自学内容网 自学内容网

css的思考

CSS思考[vue react tailwindcss]

传统css

  • 全局作用域: 一旦生效,应用于全局,造成各种各样的冲突,为了避免冲突,会写复杂的id选择器和类选择器
  • 依赖问题:引入多个css样式文件,引入的css文件会对后面的css文件造成影响
  • 打破隔离: 一旦涉及到一组样式,但是又有新的样式产生,可能会对原有的样式产生影响

解决方法

vue

在vue中,使用了scope css的方式来保证样式的唯一性,标签上不重复的生成data属性表示唯一性,编译后的css上也会生成这个选择器

react

css in js不是本身有的,是外部提供的

css in js

使用JavaScript作为语言以声明和可维护的方式描述样式。 它是一个高性能的JS到CSS编译器,它在运行时和服务器端工作。
扩展内联样式限制:支持所有的css原生功能
范围界定:唯一的选择器类名自动确定当前的 class 作用域,选择器之间无冲突
自动添加前缀:CSS 规则可以控制​自动添加前缀
代码共享:轻松地在 JS 和 CSS 之间共享常量和函数,灵活方便操作控制
轻量页面样式:只生成页面上当前 DOM 树会用到的样式

  • 在css in js中,hash会用于u企鹅人一段style是否插入,计算hash的方法就是将一段完整的css转换为hash。编写代码写的不是i最终的css,每次都需要重新序列化得到css然后再次计算hash,为渲染组件带来了额外的开销。
react中编写css的几种方法
  1. 使用className
  2. 内联样式 {{color: “red”}}
  3. css-loader(css-module)
import styles from './App.css'
const App = props => {
return (
<div className={style.app}>123</div>
  <div className={style['form-item']}>456</div>
  )
  1. css-in-js
import { css, jsx } from '@emotion/core'
const color = 'white'
const App = props => {
  return (
<div
  className={css`
    padding: 32px;
    background-color: hotpink;
    font-size: 24px;
    border-radius: 4px;
  `}
>
  This is test.
</div>
  )
}
emotion
import React from 'react';
import { css } from 'emotion'

const color = 'white'

function App() {
  return (
    <div className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}>
      This is emotion test
    </div>
  );
}

export default App;
<html lang="en">
  <head>
    <title>React App</title>
    <style data-emotion="css">
      .css-czz5zq {
        padding: 32px;
        background-color: hotpink;
        font-size: 24px;
        border-radius: 4px;
      }
    </style>
    <style data-emotion="css">
      .css-czz5zq:hover {
        color: white;
      }
    </style>
  </head>
  <body>
    <div id="root">
      <div class="css-czz5zq">This is React.js test</div>
    </div>
  </body>
</html>
  1. 将样式写模板字符串
  2. 根据模板字符串生成class名,然后写道组件的class中
  3. 将生成的class名称以及class内容放到script组件中,然后放到html的head中

postcss

postcss提供了一个解析器,能够将css转换为抽象语法树,能够为css提供额外的功能,利用postcss的功能,开发一些插件,处理css
组成: css parser css节点数 source map生成器 生成节点树串
css => parse => plugin 1 => plugin 2 => ... => stringifier => new css
读取css文件,通过parser将css解析为抽象语法树,将抽象语法树传递给任意数量的插件处理,通过诸多插件进行数据处理,插件见传递的数据就是ast树,将处理完成的ast转换为字符串。
在这里插入图片描述

tailwindcss

存在jit(just in time),在编译过程中去扫描html文件,然后生成对应的样式。


原文地址:https://blog.csdn.net/m0_73280507/article/details/142925452

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!