props์™€ attrs

Props

ํ™œ์„ฑํ™” ์—ฌ๋ถ€๋ฅผ ํ‘œํ˜„ํ•˜๊ฑฐ๋‚˜ ํŠน์ • ์Šคํƒ€์ผ์„ ์žก์•„์ค„ ๋•Œ ์œ ์šฉํ•˜๋‹ค.

import styled, { css } from "styled-components";
import { useBoolean } from "usehooks-ts";

type ButtonProps = {
  active: boolean,
};

// ์ด๋ ‡๊ฒŒ ํ•ด๋„ ๋˜๊ณ 
function background(props: ButtonProps) {
  return props.active ? "#00F" : "#FFF";
}

// ๋‚ด๋ถ€์— ์จ๋„ ๋œ๋‹ค.(์ด๋ฏธ ํƒ€์ž…์ด ์ง€์ •๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ ๋˜ํ•ด์ค„ ํ•„์š”์—†์Œ)
const Button =
  styled.button <
  ButtonProps >
  `
  background: #FFF;
  color: #000;
  border: 1px solid ${(props) => (props.active ? "#F00" : "#888")};

  ${(props) =>
    props.active &&
    css`
      background: #f00;
      color: #fff;
    `}
`;

export default function Switch() {
  const { value: active, toggle } = useBoolean(false);

  return (
    <Button type="button" onClick={toggle} active={active}>
      On/Off
    </Button>
  );
}

props.active && css์—์„œ css ๋Š” ์จ๋„ ๋˜๊ณ  ์•ˆ์จ๋„ ๋œ๋‹ค. ํƒ€์ž… ํ™•์žฅ์˜ ๋„์›€์„ ๋ฐ›๊ธฐ์œ„ํ•ด ์‚ฌ์šฉํ•  ๋ฟ์ด๋‹ค.

๊ณต์‹ ๋ฌธ์„œ ์˜ˆ์‹œ

input ์ปดํฌ๋„ŒํŠธ์˜ ๋ชจ๋“  ํ”„๋กœํผํ‹ฐ๊ฐ€ DOM ๋…ธ๋“œ์— ์ „๋‹ฌ๋œ๋‹ค.

์—ฌ๊ธฐ์„œ inputColor prop์€ DOM์„ ํ†ตํ•˜์ง€ ์•Š์ง€๋งŒ type๊ณผ defaultValue๋Š” DOM์„ ํ†ตํ•œ๋‹ค. ๋น„ํ‘œ์ค€ ์†์„ฑ์€ ์ž๋™์œผ๋กœ ํ•„ํ„ฐ๋ง๋˜๋Š” ๊ฒƒ์ด๋‹ค.

const Input = styled.input`
  padding: 0.5em;
  margin: 0.5em;
  color: ${(props) => props.inputColor || "palevioletred"};
  background: papayawhip;
  border: none;
  border-radius: 3px;
`;

render(
  <div>
    <Input defaultValue="@probablyup" type="text" />
    <Input defaultValue="@geelen" type="text" inputColor="rebeccapurple" />
  </div>
);

attrs

attrs๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์†์„ฑ์„ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ค. ๋ฒ„ํŠผ์—์„œ ๋˜๊ฒŒ ์ž์ฃผ ์“ฐ์ธ๋‹ค.

import styled from "styled-components";

// type ์†์„ฑ์„ ์ „๋‹ฌ ๋ฐ›์•˜๋‹ค.
const Button = styled.button.attrs({
  type: "button",
})`
  border: 1px solid #888;
  background: transparent;
  cursor: pointer;
`;

export default Button;

๊ณต์‹ ์‚ฌ์ดํŠธ ์˜ˆ์‹œ

const Input = styled.input.attrs((props) => ({
  // ์ •์ ์ธ props๋ฅผ ์ •์˜ํ•  ์ˆ˜๋„ ์žˆ๊ณ 
  type: "text",
  // ๋™์ ์ธ props๋ฅผ ์ •์˜ํ•  ์ˆ˜๋„ ์žˆ๋‹ค.
  size: props.size || "1em",
}))`
  color: palevioletred;
  font-size: 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;

  /* ์—ฌ๊ธฐ์—์„œ ๋™์ ์œผ๋กœ ๊ณ„์‚ฐ๋œ ํ”„๋กญ์„ ์‚ฌ์šฉํ•œ๋‹ค */
  margin: ${(props) => props.size};
  padding: ${(props) => props.size};
`;

render(
  <div>
    <Input placeholder="A small text input" />
    <br />
    <Input placeholder="A bigger text input" size="2em" />
  </div>
);

Last updated