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

查看:95
本文介绍了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天全站免登陆