styled-components 中的这个语法到底是什么意思?

what does this syntax in styled-components actually mean?

我刚开始使用 styled-components,看到它们调用了我认为是这样的函数:

import styled from "styled-components"

const Button = sytled.button` <--- this 
    // css goes here
`

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

这就是您为 <button> 元素设置 CSS 规则的方式。

那么你可以这样使用它:

<Button>Hello world</Button> 

并且您在上面编写的所有样式都将应用于所有 <Button> 元素

Styled-components 是一个用于设置 React 组件样式的库。

import styled from "styled-components"

const Button = sytled.button` <--- this 
  // css goes here
 `;

 `` <-- these are template literals which was introduced in ES6.

styled 在这里是一个对象,当您说 styled.button 时,这意味着我们正在为 html 标签设置样式。因此,您可以设置 div、容器、h1 等样式。您想使用标准 css 设置这些 html 标签的样式,而样式化组件会为其创建一个随机类名。

假设您想要设置 div 的样式。您将其命名为包装器。命名惯例是首字母始终大写。

const Wrapper = styled.div`
   background: #c0c0aa;  /* fallback for old browsers */
   background: -webkit-linear-gradient(to right, #1cefff, #c0c0aa);  /* Chrome 10-25, Safari 5.1-6 */
   background: linear-gradient(to right, #1cefff, #c0c0aa); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
   height: 100%;
   width: 100%;
 `;

现在你可以将你的内容包装在 react 的 render() 中了。

 <Wrapper>
  //Your code in render of react class goes here
  //thus instead of <div className = 'Wrapper'>
  //you use the above code
  //styled-components automatically generates random classnames solving major problems

 </ Wrapper>

有关更多信息,请参阅 Max Stoiber 在 React Amsterdam 上的主题演讲。 https://www.styled-components.com/docs/basics#motivation

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

  1. 包含所有字符串部分的数组 介于 ${variables}.
  2. 之间
  3. 模板的第一个 ${variable}
  4. 模板的第二个 ${variable}
  5. 等...

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

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

这样称呼

tag`Hello, ${name}! I found ${count} results.`

产生与

相同的结果
`Hello, ${name}! I found ${count} results.`

并且提供给标记函数的参数是 ['Hello, ', '! I found ', ' results.']namecount