스타일이 지정된 구성 요소가 필요하지 않을 수도 있습니다.

styled-components 구성 요소를 휘젓는 데는 꽤 좋을 수 있지만 구식 CSS에 더 익숙한 나와 같은 오래된 방귀에게는 CSS Modules 을 사용하는 것을 선호합니다.

CSS 모듈을 사용할 때 우리는 어떤 것이 더 간단하지만(미디어 쿼리) 어떤 것은 그렇게 쉽지 않다는 것을 빨리 알게 됩니다($@^%는 테마를 어떻게 사용합니까?).

테마



styled-components에는 좋은 ThemeProvider이 있습니다. 서버 어딘가에서 JSON을 가져와 ThemeProvider에 전달하면 스타일에 사용할 수 있습니다.

우리도 할 수 있습니다. 먼저 Theme Context 컴포넌트를 만듭니다. 전체가 4줄이고, 한 줄은 비어 있고, 어쨌든 첫 번째 줄은 필요하지 않을 수도 있습니다.

import { createContext } from "react";

export const ThemeContext = createContext();
export const ThemeProvider = ThemeContext.Provider;


이를 사용하기 위해 ThemeProvider를 가져온 다음 스타일을 지정해야 하는 일부 JSX를 래핑합니다.

import { ThemeProvider } from "./ThemeContext";

<ThemeProvider value={theme}>
  <Button>Press</Button>
</ThemeProvider>


다음은 테마를 사용하는 Button 구성 요소의 간단한 예입니다.

import React, { useContext } from "react";
import styles from "./Button.module.css";
import { ThemeContext } from "./ThemeContext";

export const Button = (props) => {
  const theme = useContext(ThemeContext);

  const style = {
    "--bg-color": theme.backgroundColor,
    "--fg-color": theme.foregroundColor,
    ...props.style
  };

  return (
    <button
      className={styles.Button}
      style={style}
    />
  );
};


테마에 필요한 값은 style 속성을 통해 CSS에 전달됩니다. CSS 모듈은 다음과 같이 CSS variables을 사용할 수 있습니다.

.Button {
  color: var(--fg-color);
  background-color: var(--bg-color);
}


소품 기반 적응



때로는 일부 소품을 기반으로 구성 요소의 스타일을 변경하고 싶을 때가 있습니다. 이것은 CSS를 사용하면 매우 쉬워집니다.

<Button size="large">
  Primary Large
</Button>


CSS

.Button {
  font-size: 14px;
}

.Button[data-size=large] {
  font-size: 16px;
}


Window.matchMedia



마지막 트릭은 다소 드물지만 미리 중단점을 알 수 없는 문제에 부딪쳤고 컴포넌트에 클래스를 추가해야 하는지 여부를 결정하기 위해 javascript에서 로직을 사용해야 했습니다.

Window.matchMedia 이 문제를 해결할 수 있었습니다.

이렇게 하면 내 구성 요소가 breakpoint 소품을 허용하고 창이 중단점보다 작은 경우 CSS 클래스를 추가할 수 있습니다.

const maxWidth = width =>
  window.matchMedia(`(max-width: ${width}px)`).matches;

const getItemClasses = breakpoint => {
  const names = [styles.Item];
  if (maxWidth(breakpoint)) names.push(styles.ItemSmall);
  return names.join(" ");
};

return (
  <div className={getItemClasses(breakpoint)}>{children}</div>
);


결론



이 트릭은 내가 사용했지만 CSS 모듈을 대신 사용할 수 있게 해주는 styled-components의 기능을 다루었습니다. 유용하게 사용하시기 바랍니다.

좋은 웹페이지 즐겨찾기