关于css:在-Svelte-中使用-CSSinJS

4次阅读

共计 1739 个字符,预计需要花费 5 分钟才能阅读完成。

你即使不须要,但你能够。

留神:原文发表于 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 解决两者一起应用。


< The End >

​- 窗明几净,静候时日变迁 –

正文完
 0