styled-components 中的这种语法实际上意味着什么?

Str*_*vaz 6 reactjs styled-components

我刚刚开始使用样式组件,发现它们调用了我认为的函数,如下所示:

import styled from "styled-components"

const Button = sytled.button` <--- this 
    // css goes here
`
Run Code Online (Sandbox Code Playgroud)

我以前从未见过这种语法,想知道是否有人可以向我指出一些关于它实际上是什么的文档。

Uma*_*gon 5

它称为标记模板文字。“标签”是模板文字之前的函数,调用它时其参数是模板和模板的变量。参数如下:

  1. 包含之间所有字符串部分的数组${variables}
  2. 首先${variable}是模板。
  3. 第二${variable}模板的
  4. ETC...

例如,我编写了一个名为 的函数tag,它的作用与当您未指定任何标记函数(也称为其默认函数)时用于处理的函数模板文字相同:

function tag(stringParts, ...values){
  return stringParts.reduce((accum, part, index) => accum + values[index-1] + part);
}
Run Code Online (Sandbox Code Playgroud)

这样称呼它

tag`Hello, ${name}! I found ${count} results.`
Run Code Online (Sandbox Code Playgroud)

产生相同的结果

`Hello, ${name}! I found ${count} results.`
Run Code Online (Sandbox Code Playgroud)

传递给标签函数的参数是['Hello, ', '! I found ', ' results.']namecount