nanostyled 소개: JS의 CSS가 아니라 JS의 CSS

Nanostyled는 스타일화된 구성 요소를 구축하는 데 사용되는 작은 라이브러리입니다. (< 1KB는 통일되지 않았습니다.)JS 라이브러리의 유연하고 구성 요소 기반 CSS API를 일반 CSS의 낮은 오버헤드와 결합시키려 합니다.
저비용
유연한 구성 요소 기반 API
일반 CSS


JS의 CSS


나노급


JS 라이브러리의 CSS를 계발하는 것처럼 -💕 styled-components - nanostyled에서는 복잡한 기본 스타일로 UI 요소를 구성한 다음 도구를 사용하여 응용 프로그램 전체에서 스타일을 조정할 수 있습니다.
<Button>A nice-looking button</Button>
<Button color="blue">A nice-looking button that is blue.</Button>
JS 라이브러리의 CSS와 달리 nanostyled는 JS에서 어떤 CSS도 사용하지 않습니다.반면에 이것은 기능성 CSS 프레임워크, 예를 들어 Tachyons 또는 Tailwind을 수반하는 것으로 설계되었다.Nanostyled는 기능 CSS를 지루하지 않게 하고 도구 제어의 구성 요소에서 쉽게 추출할 수 있도록 합니다.
설치 및 사용에 대한 자세한 내용은 nanostyled on npm을 참조하거나 자세한 컨텍스트를 계속 참조하십시오.

기능 CSS?
기능성 CSS 프레임워크의 기본 전제는 작은 CSS 유틸리티 클래스를 조합해서 복잡한 스타일을 구축할 수 있다는 것입니다.
플래그에는 초광속 서브가 있는 버튼이 다음과 같이 표시될 수 있습니다.
<button class="bg-blue white br2 pa2">Button</button>
파란색 배경, 흰색 텍스트, 필렛(br2) 및 모든 모서리의 채우기(pa2)가 있는 버튼입니다.

holy hell this is the worst thing I've ever seen
-Adam Wathan, author of Tailwind.css


이거 진짜야.기능성 CSS는 보기 흉하다. 수십 년 동안의 최선의 실천에 어긋난다. 내용과 양식을 분리하는 것이다.
다른 한편, 기능성 CSS 스타일을 사용하면 대형 프로젝트에서 시각적 일치성을 잘 확장하고 새로운 UI 요소를 쉽게 구축할 수 있으며 새로운 CSS를 작성하지 않아도 된다.아담 와탄, 순풍의 창작자, defends the approach elegantly here.
Nanostyled는 기능 CSS를 구성 요소로 추상화하기 쉬우며 어떠한 장점도 포기하지 않습니다.

React에서 기능성 CSS를 사용하여 유연한 구성 요소를 구축하는 것이 어려운 이유
함수식 CSS를 사용하는 번거로움을 줄이기 위해 포함된 React 구성 요소에서 긴 클래스 문자열을 추출할 수 있습니다.
const Button = ({ className = '', ...rest }) => (
  <button className={`bg-blue white br3 pa2 fw7 ${className}`} {...rest} />
)
이 예에서 문제는 서로 다른 배경색으로 우리의 <Button>을 과장하는 좋은 방법이 없다는 것이다.비록 className 아이템을 받아들였지만 <Button className="bg-red" />을 쓰면 반드시 빨간색 버튼이 나타나지 않는다.
맥스 스토이버(Max Stoiber)의 최근 작품은 이유를 잘 설명했다.

How well do you know CSS? Given these classes:
.red { color: red; }
.blue { color: blue; }
Which color would these divs be?
<div class="red blue">
<div class="blue red">


정답은 두 div 모두 파란색으로 응답자의 57%가 틀렸다.
HTML만 보고 답을 알 수는 없다.충돌하는 두 CSS 클래스가 동일한 특성을 가지는 경우 태그의 순서가 연관되지 않으므로 CSS를 확인해야 합니다.어떤 종류가 승리하는지는 스타일시트에서 마지막으로 어떤 종류를 정의했는지에 달려 있다.
따라서 강력한 <Button>을 구축하기 위해서는
  • 일부 주식 CSS 클래스의 스타일 설명
  • 은 일부 재고 클래스를
  • 으로 대체하는 편리한 API를 공개했습니다.
    두 번째 요구는 직감에 어긋나는 계급 충돌을 피하는 관건이다. 맥스의 여론조사처럼 이것도 나노스타일드가 일을 쉽게 하는 부분이다.

    나노 스타일과 패션 아이템으로 부드러운 부품 구축
    Nanostyled는 선택한 기능 CSS 프레임의 클래스 이름에 스타일 도구를 매핑하는 방식으로 작동합니다.
    스타일 아이템은 사용자의 취향에 따라 명명할 수 있으며 각 아이템은 임의의 수량의 CSS 클래스를 포함할 수 있습니다.

    나이미 단추
    import nanostyled from 'nanostyled';
    // This example uses CSS classes from Tachyons
    import 'tachyons/css/tachyons.css';
    
    // A Button with three style props:
    const Button = nanostyled('button', {
      color: 'white',
      bg: 'bg-blue',
      base: 'fw7 br3 pa2 sans-serif f4 bn input-reset'
    });
    
    const App = () => (
      <div>
        <Button>Base Button</Button>
        <Button bg="bg-yellow">Yellow Button</Button>
      </div>
    );
    
    /* rendering <App /> produces this markup:
    <div>
      <button class="white bg-blue fw7 br3 pa2 sans-serif f4 bn input-reset">Base Button</button>
      <button class="white bg-yellow fw7 br3 pa2 sans-serif f4 bn input-reset">Yellow Button</button>
    </div>
    */
    
    nanostyled(element)이 나타나면 스타일 도구를 사용하고 HTML 클래스 문자열에 결합합니다.
    어떤 스타일의 도구를 사용하느냐는 완전히 너에게 달려 있다.위의 <Button>에는 API가 하나 있는데 colorbg 아이템을 통해 색상이나 배경색의 스타일을 쉽게 재설정할 수 있지만 base 아이템을 완전히 다시 쓰지 않으면 다른 스타일을 바꾸기 어렵다.

    유연한 나노 버튼
    더 많은 패션 아이템을 사용함으로써 우리는 더욱 유연한 단추를 만들 수 있다.
    import nanostyled from 'nanostyled';
    import 'tachyons/css/tachyons.css';
    
    const FlexibleButton = nanostyled('button', {
      color: 'white', // white text
      bg: 'bg-blue', // blue background
      weight: 'fw7', // bold font
      radius: 'br3', // round corners
      padding: 'pa2', // some padding
      typeface: 'sans-serif', // sans-serif font
      fontSize: 'f4', // font size #4 in the Tachyons font scale
      base: 'bn input-reset', // remove border and appearance artifacts
    });
    
    주식 <FlexibleButton />을 나타내면 더욱 간단한 상대 주식과 같은 표시가 생길 것이다.그러나 재지정 스타일을 렌더링하는 것은 훨씬 쉽습니다.
    <FlexibleButton
      bg="bg-light-green"
      color="black"
      weight="fw9"
      radius="br4"
    >
      Button with a green background, black text, heavier font, and rounder corners
    </FlexibleButton>
    
    스타일 아이템에 사용할 계획이 없는 변체가 필요할 때 className 아이템을 사용할 수 있습니다.
    <FlexibleButton className="dim pointer">
      A button that dims on hover and sets the cursor to 'pointer'
    </FlexibleButton>
    

    여러 구성 요소에 걸쳐 스타일 아이템 공유
    nanostyled를 사용하여 다중 구성 요소 UI 패키지를 구축하고 있다면, 모든 구성 요소에서 최소한 기본적인 스타일 도구를 공유하는 것을 권장합니다.그렇지 않으면 어떤 구성 요소가 color 도구를 지원하고 어떤 구성 요소가 지원하지 않는지 기억하기 어렵다.
    나는 보통 여기서부터 시작한다.
    import React from "react";
    import ReactDOM from "react-dom";
    import nanostyled from "nanostyled";
    import "tachyons/css/tachyons.css";
    
    // The keys in this styleProps will determine which style props
    // our nanostyled elements will accept:
    const styleProps = {
      bg: null,
      color: null,
      margin: null,
      padding: null,
      font: null,
      css: null
    };
    
    /* 
    Why choose those keys, in particular? For everything except `css`, 
    it's because the elements in the UI kit probably will have some default 
    bg, color, margin, padding, or font we'll want to be able to easily override via props.
    
    The `css` prop is an exception. I just like being able to use it instead of `className`.
    */
    
    // Box will support all styleProps, but only use them when we explicitly pass values
    const Box = nanostyled("div", styleProps);
    /*
    <Box>Hi!</Box>
    renders <div>Hi!</div>
    
    <Box color="red">Hi!</Box>
    renders <div class="red">Hi!</div>
    */
    
    // Button will also support all styleProps, and will use some of them by default
    const Button = nanostyled("button", {
      ...styleProps,
      bg: "bg-blue",
      color: "white",
      padding: "pa2",
      font: "fw7",
      // I use a 'base' prop to declare essential component styles that I'm unlikely to override
      base: "input-reset br3 dim pointer bn"
    });
    /*
    <Button>Hi!</Button>
    renders
    <button class="bg-blue white pa2 dim pointer bn input-reset>Hi!</button>
    */
    
    // Heading uses styleProps, plus some extra props for fine-grained control over typography
    const Heading = nanostyled("h1", {
      ...styleProps,
      size: "f1",
      weight: "fw7",
      tracking: "tracked-tight",
      leading: "lh-title"
    });
    
    // Putting them all together....
    const App = () => (
      <Box padding="pa3" font="sans-serif">
        <Heading>Styling with Nanostyled</Heading>
        <Heading tracking={null} tag="h2" size="f3" weight="fw6">
          A brief overview
        </Heading>
        <Heading tag="h3" weight="fw4" size="f5" tracking={null} css="bt pv3 b--light-gray">
          Here are some buttons:
        </Heading>
        <Button>Base Button</Button>
        <Button css="w-100 mv3" padding="pa3" bg="bg-green">
          Wide Green Padded Button
        </Button>
        <Box css="flex">
          <Button css="w-50" margin="mr2" bg="bg-gold">
            50% Wide, Gold
          </Button>
          <Button css="w-50" margin="ml2" bg="bg-red">
            50% wide, Red
          </Button>
        </Box>
      </Box>
    );
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    
    이 완전한 예는 available on CodeSandbox으로 당신이 실험을 진행할 수 있도록 제공됩니다.
    Nanostyled는 on npm에서 얻을 수 있으며 GitHub을 통해 도서관에 투고할 수 있습니다.

    좋은 웹페이지 즐겨찾기