Tagged Template Literal

2024. 6. 7.

sytled-componentsλ₯Ό μ‚¬μš©ν•΄λ΄€λ‹€λ©΄ λ‹€μŒκ³Ό 같은 μ½”λ“œλ₯Ό 본적이 μžˆμ„ 것이닀.

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #bf4f74;
`;

λ‹€μŒκ³Ό 같은 μ½”λ“œλ₯Ό Tagged Template Function , tag function이라고 λΆ€λ₯Έλ‹€.

Template literals (Template strings)

κΈ°λ³Έ νƒ¬ν”Œλ¦Ώ λ¦¬ν„°λŸ΄λ‘œ μž‘μ„±ν•˜λŠ” λ¬Έμžμ—΄μ€ λ‹€μŒκ³Ό κ°™λ‹€.

const a = 5;
const b = 10;
 
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
 
// "Fifteen is 15 and
// not 20."

Tagged templates

πŸ–‹οΈ

MDN

보닀 κ³ κΈ‰ ν˜•νƒœμ˜ ν…œν”Œλ¦Ώ λ¦¬ν„°λŸ΄μ€ νƒœκ·Έκ°€ μ§€μ •λœ ν…œν”Œλ¦Ώμž…λ‹ˆλ‹€.

νƒœκ·Έλ₯Ό μ‚¬μš©ν•˜λ©΄ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ ν…œν”Œλ¦Ώ λ¦¬ν„°λŸ΄μ„ ꡬ문 뢄석할 수 μžˆμŠ΅λ‹ˆλ‹€. νƒœκ·Έ ν•¨μˆ˜μ˜ 첫 번째 μΈμˆ˜λŠ” λ¬Έμžμ—΄ κ°’μ˜ 배열을 ν¬ν•¨ν•©λ‹ˆλ‹€. λ‚˜λ¨Έμ§€ μΈμˆ˜λŠ” ν‘œν˜„μ‹κ³Ό 관련이 μžˆμŠ΅λ‹ˆλ‹€.

그러면 νƒœκ·Έ ν•¨μˆ˜λŠ” μ΄λŸ¬ν•œ μΈμˆ˜μ— λŒ€ν•΄ μ›ν•˜λŠ” 연산을 μˆ˜ν–‰ν•˜κ³  μ‘°μž‘λœ λ¬Έμžμ—΄μ„ λ°˜ν™˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€. (λ˜λŠ” λ‹€μŒ 예제 쀑 ν•˜λ‚˜μ— μ„€λͺ…λœ κ²ƒμ²˜λŸΌ μ™„μ „νžˆ λ‹€λ₯Έ 것을 λ°˜ν™˜ν•  μˆ˜λ„ μžˆμŠ΅λ‹ˆλ‹€.)

νƒœκ·Έμ— μ‚¬μš©λ˜λŠ” ν•¨μˆ˜μ˜ 이름은 μ›ν•˜λŠ” λŒ€λ‘œ 지정할 수 μžˆμŠ΅λ‹ˆλ‹€.

const person = 'Mike';
const age = 28;
 
function myTag(strings, personExp, ageExp) {
  const str0 = strings[0]; // "That "
  const str1 = strings[1]; // " is a "
  const str2 = strings[2]; // "."
 
  const ageStr = ageExp < 100 ? 'youngster' : 'centenarian';
 
  // We can even return a string built using a template literal
  return `${str0}${personExp}${str1}${ageStr}${str2}`;
}
 
const output = myTag`That ${person} is a ${age}.`;
 
console.log(output);
// That Mike is a youngster.

ν™œμš© 사둀

styled-component

https://marpple.github.io/rune/