ES6 中函数后面的模板文字(反引号)的目的是什么? [英] What is the purpose of template literals (backticks) following a function in ES6?

查看:17
本文介绍了ES6 中函数后面的模板文字(反引号)的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 GraphQL 中,您可以编写如下内容来定义查询:

In GraphQL you can write something like this to define a query:

const USER_QUERY = gql`
  {
    user(id: 2) {
      name
    }
  }
`

在样式组件中,您可以像这样定义样式组件:

In styled components you can define a styled component like this:

const Button = styled.button`
    background-color: papayawhip;
`

这是什么语法?我知道使用模板文字,您可以使用以下语法子变量: ${foo} 但我从未见过使用它.任何指导将不胜感激.

What is this syntax? I know with template literals you can sub in variables with this syntax: ${foo} but I have never seen this used. Any guidance would be appreciated.

推荐答案

这些是 标记模板文字.背包之前的部分是对将被调用以处理字符串的函数的引用.

These are tagged template literals. The part before the backpacks is a reference to a function that will be called to process the string.

该函数将变量(${} 部分)作为参数以及围绕分解为数组的变量的字符串片段传递给函数.函数的返回值成为模板的值.由于这种非常通用的格式,您几乎可以使用该函数执行任何操作.这是一个快速而肮脏的示例,它采用变量(为方便起见收集到数组中),使它们大写,然后将它们放回字符串中:

The function is passed the variables (the ${} parts) as arguments as well as the pieces of the string that surround the variables broken into an array. The return value of the function becomes the value of the template. Because of this very generalized format, you can do almost anything with the function. Here's a quick and dirty example that takes the variables (gathered into an array for convenience), makes them uppercase, and puts them back in the string:

function upperV(strings, ...vars) {
  /* make vars uppercase */
  console.log("vars: ", vars)       // an array of the passed in variables
  console.log("strings:", strings)  // the string parts

  // put them together
  return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
}

let adverb = "boldly"
let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
console.log(output)

这篇关于ES6 中函数后面的模板文字(反引号)的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆