当前位置:
首页 > 网站开发 > JavaScript教程 >
-
在 Svelte 中使用 CSS-in-JS
注意:原文发表于2018-12-26,随着框架不断演进,部分内容可能已不适用。
CSS 是任何 Web 应用程序的核心部分。
宽泛而论,如果一个 UI 框架没有内置向组件添加样式的方式,那么它就是半成品。
这便是为何 Svelte 允许你在组件的 <style>
标签中添加 CSS 的缘故。
将 CSS 与标记共存,意味着我们可以解决开发人员在编写 CSS 时遇到的最大问题,在不引入新的问题的同时,还提供极佳的开发体验。
但是 Svelte 的样式处理确实存在一些限制,在组件之间共享样式或者应用级优化都艰难重重。
这些是我们计划在未来版本中解决的,不过与此同时,如果你亟需这些功能的话,你可以使用与框架无关的 CSS-in-JS 库。
示例
在这里,我们用 Emotion 来生成可以跨多个组件中使用的范围受限的类名:
App.svelte
<script>
import { comicSans, link } from './styles.js';
import Hero from './Hero.svelte';
</script>
<Hero/>
<div class={comicSans}>
<p>
Did you enjoy your lunch, mom? You drank it fast enough.
I know, I just call her Annabelle cause she's shaped like a…
she's the belle of the ball! YOU'RE the Chiclet! Not me.
Caw ca caw, caw ca caw, caw ca caw!
A Colombian cartel that WON'T kidnap and kill you.
You go buy a tape recorder and record yourself for a whole day.
<a class={link} href="https://bluthipsum.com/">I think you'll be surprised at some of your phrasing.</a>
</p>
</div>
Hero.svelte
<script>
import { title, comicSans, box } from './styles.js';
</script>
<div class="{title} {comicSans}">
<h1>
<div class={box}>
<div class={box}>
<div class={box}>CSS</div>
in JS
</div>
in HTML
</div>
</h1>
</div>
styles.js
import emotion from 'emotion/dist/emotion.umd.min.js';
const { css } = emotion;
const brand = '#74D900';
export const title = css`
color: ${brand};
font-size: 1em;
white-space: nowrap;
`;
export const comicSans = css`
font-family: 'Comic Sans MS', cursive;
`;
export const box = css`
position: relative;
display: inline-block;
border: 2px solid ${brand};
line-height: 1;
padding: 4px;
border-radius: 4px;
`;
export const link = css`
color: inherit;
font-weight: bold;
text-decoration: none;
border-bottom: 1px solid ${brand};
&:hover {
text-decoration: none;
background: ${brand};
}
`;
不过一定要提醒你的是,大多数的 CSS-in-JS 库都有一个运行时,许多库在构建时,不支持将样式静态提取到单独的 .css
文件中(这对于获取最佳性能至关重要)。
因此,仅在你的应用有迫切需要时才建议使用 CSS-in-JS!
请注意,你也可以混合搭配 CSS-in-JS 和 Svelte 内置的 CSS 处理两者一起使用。
出处:https://www.cnblogs.com/qianduanziyu/p/svelte-css-in-js.html
最新更新
Python获取微信好友数据
Python 的排序方法 sort 和 sorted 的区别
WinForm轻松实现自定义分页 (转载)
Mac系统下使用brew搭建PHP(LNMP/LAMP)开发环境
在win系统安装配置 Memcached for PHP 5.3 图文
箱图在数据预处理中的应用
Python WEB开发:用Tornado框架制作简易【表
自从学会了用python解析视频,都不用去找
Python代码阅读(第50篇):对列表间隔取
Python爬虫+数据分析+可视化展示,分析《
MongoDB常用命令(2)
MongoDB基本介绍与安装(1)
SQLServer触发器调用JavaWeb接口
SQL Server索引的原理深入解析
SqlServer2016模糊匹配的三种方式及效率问题
SQL中Truncate的用法
sqlserver 多表关联时在where语句中慎用tri
链接服务器读取Mysql---出现消息 7347,级别
SQL Server解惑——为什么你拼接的SQL语句换
MySQL视图了解一下
laf.js - 开源的云开发框架(README.md)
javascript创建对象
Node.js 源码分析 - 从 main 函数开始
Node.js 源码分析 - 原生模块(C++模块)的注册
ECharts图标中用的js相关的处理方法
GoJS 使用笔记
单元测试 - 测试场景记录
Node.js 源码分析 - 加载 js 文件
ES6入门
聊聊动效降级