programing

css 모듈을 사용하여 둘 이상의 스타일 이름을 정의하는 방법

prostudy 2022. 3. 15. 20:53
반응형

css 모듈을 사용하여 둘 이상의 스타일 이름을 정의하는 방법

css 모듈을 사용하여 요소에 대해 여러 클래스를 사용하려고 한다.이거 어떻게 하지?

function Footer( props) {
    const { route } = props;
    return (
        <div className={styles.footer}>
            <div className={styles.description, styles.yellow}>
              <p>this site was created by me</p>
            </div>
            <div className={styles.description}>
              <p>copyright nz</p>
            </div>
        </div>
    );
}

css 모듈을 사용하여 다음과 같이 여러 클래스를 추가할 수 있다.

className={`${styles.description} ${styles.yellow}`}

예)

function Footer( props) {
    return (
        <div className={styles.footer}>
            <div className={`${styles.description} ${styles.yellow}`}>
              <p>this site was created by me</p>
            </div>
        </div>
    );
}

react-css-modules를 사용하여 일반 클래스 이름 구문을 사용할 수 있다.

<div styleName='description yellow'>

그리고 당신이 지정한다.allowMultiple: true복수 클래스용

스페이스와 결합할 배열을 사용할 수 있다.

<div className={[styles.App, styles.bold, styles['d-flex-c']].join(' ')}>

나는 @steven iseki가 제안한 것과 같은 템플릿 리터럴을 사용하는 것보다 이것을 더 선호한다. 왜냐하면 클래스를 포장하지 않고도 추가하고 제거하는 것이 더 쉽기 때문이다.${}매번

하지만 어떤 이유에서인지 클래스를 많은 요소에 추가한다면 더 쉽게 만들 수 있는 더 높은 순서 함수를 작성할 수 있다.

import React from 'react';
import styles from './Person.module.css';

console.log(styles);
// sample console output =>
// {
//   App: 'App_App__3TjUG',
//   'd-flex-c': 'App_d-flex-c__xpDp1',
// }


// func below returns a function that takes a list of classes as an argument
// and turns it in an array with the spread operator and reduces it into a spaced string

const classLister = styleObject => (...classList) =>
  classList.reduce((list, myClass) => {
    let output = list;
    if (styleObject[myClass]) {
      if (list) output += ' '; // appends a space if list is not empty
      output += styleObject[myClass]; 
      //Above: append 'myClass' from styleObject to the list if it is defined
    }
    return output;
 }, '');

const classes = classLister(styles); 
// this creates a function called classes that takes class names as an argument
// and returns a spaced string of matching classes found in 'styles'

사용법

<div className={classes('App', 'bold', 'd-flex-c')}>

아주 깔끔하고 읽기 쉬워 보인다.

DOM에 렌더링하면

<div class="App_App__3TjUG App_d-flex-c__xpDp1">
/* Note: the class 'bold' is automatically left out because
   in this example it is not defined in styles.module.css 
   as you can be observe in console.log(styles) */

역시

그리고 조건부로 생성된 클래스를 ...확산 연산자를 통해 클래스의 인수로 사용되는 배열로 배치하여 조건과 함께 사용할 수 있다.

사실 이것에 대답하는 동안 나는 npm 모듈을 발행하기로 결정했다. 왜 그럴 수 없는가.

와 함께 받아라!

npm install css-module-class-lister

나는 학급 이름 패키지를 사용하는 것을 적극 추천한다.믿을 수 없을 정도로 가벼우며(600바이트 분량) 종속성이 없음:

import classnames from 'classnames';

Function footer(props) {
  ...
  <div className={classnames(styles.description, styles.yellow)}>
}

심지어 실수로 추가될 수 있는 문자열을 연결할 필요 없이 (를 들어 어두운 테마 클래스를 추가하는 경우) 클래스 이름을 조건부로 추가할 수 있다는 추가 이점이 있다.undefined또는false클래스:

  <div className={classnames(styles.description, {styles.darkTheme: props.darkTheme })}>

대괄호를 추가하여 클래스를 배열로 만들고 ''을(를) 제거하려면' 조인()을 추가하십시오.

function Footer( props) {
    const { route } = props;
    return (
        <div className={styles.footer}>
            <div className={ [styles.description, styles.yellow].join(' ') }>
              <p>this site was created by me</p>
            </div>
            <div className={styles.description}>
              <p>copyright nz</p>
            </div>
        </div>
    );
}

위안하오치앙대답에 덧붙여 다음과 같은 기능을 통해 더욱 쉽게 작업할 수 있다.

const classes = (classNames: Array<string> | string): string => classnames((Array.isArray(classNames) ? classNames : classNames.split(' ')).map(x => styles[x]));

이 작업은 배열 또는 문자열(그 다음 문자열 배열로 분할됨)을 사용하고 가져온 문자열을 사용하기 때문에 최종 클래스 이름(현재 모듈로 범위 지정됨)을 반환하는 것이다.styles물론).

이렇게 사용하는 경우:

<div className={classes(['description', 'dark-theme', 'many', 'more', 'class-names'])}>

또는 단일 문자열(예: TailwindCSS 사용 시 많은 클래스를 사용하는 경우 핸들링):

<div className={classes('description dark-theme many more class-names')}>

클래스 이름 패키지를 사용하는 경우 스타일을 조건부로 적용하려면 다음과 같이 대괄호가 있는 동적 속성 키를 사용하십시오.

<div className={classNames(styles.formControl, { [styles.hidden]: hidden })}>
</div>

내 경우에 가장 좋은 해결책은 아래의 기능이다.부대가 파괴되면 공간이 있는 수업으로 돌려줄 수 있거든

export function clx(...classes) {
  return classes.join(" ");
}
// className={clx('border', styles.form, styles.h1, 'classe-4')}
// class="border form_CDE h1_AB"

className 속성 앞에 있는 class name 결합의 경우, "clsx"를 사용할 수 있으며, 이 패키지를 사용하는 것은 쉽다.

import clsx from 'clsx';
// Strings
clsx('foo', 'bar', 'baz'); // 'foo bar baz'

// Objects
clsx({ foo:true, bar:false, baz:true });// 'foo baz'

이 주소에서 패키지를 찾을 수 있다: https://github.com/lukeed/clsx

클래스에 가입할 클래스 이름 패키지 설치함께 이름

npm install classnames --save

해결책:

import cx from 'classnames';

Function footer(props) {
 ...
 <div className={cx(styles.description, styles.yellow)}>
}

간단히 하다

<div className={style.smallFont + " " + style.yellowColor}>

끈 연결

이것은 통제 불능이 될 수 있다:

 className={`${styles.description} ${styles.yellow}`}

클래스를 설정하고 다음을 호출하는 함수를 만드는 것이 좋다.

const setClass = (classes: string[]) => {
    return classes.map((className) => styles[className]).join(" ");
  };
<article className={setClass(["student", "student-expand-view-layout"])}>

space(' ') ->와 함께 문자열연결을 사용할 수 있다.

<div className={classes.centerFlexY + ' ' + classes.searchTabs} />

여러 스타일을 사용하여 추가 클래스를 정의하지 않는 이유는?맘에 들다

div .descyellow{
  background_color: yellow;
  style...
}

그 다음에

<div class="descyellow">

참조URL: https://stackoverflow.com/questions/33949469/using-css-modules-how-do-i-define-more-than-one-style-name

반응형