ES6 中函数后面的模板文字(反引号)的目的是什么?
What is the purpose of template literals (backticks) following a function in ES6?
在 GraphQL 中,您可以编写如下内容来定义查询:
const USER_QUERY = gql`
{
user(id: 2) {
name
}
}
`
在样式组件中,您可以像这样定义样式组件:
const Button = styled.button`
background-color: papayawhip;
`
这是什么语法?我知道使用模板文字可以使用以下语法子变量:${foo}
但我从未见过这种用法。任何指导将不胜感激。
模板文字有一个附加功能,称为标记模板。这就是开始反引号之前的前缀。前缀实际上是一个函数的名称 - 该函数被传递给模板字符串的常量部分和内插值(${}
部分中的内容)并且可以将结果字符串处理成它想要的任何东西(尽管通常是另一个字符串,不一定是)。
有关标记模板如何工作的更多详细信息,请参阅 this page on MDN。
这些是tagged template literals。背包之前的部分是对将调用以处理字符串的函数的引用。
函数将变量(${}
部分)作为参数以及围绕变量的字符串片段传递到一个数组中。函数的 return 值成为模板的值。由于这种非常通用的格式,您几乎可以使用该函数做任何事情。这是一个快速而肮脏的示例,它获取变量(为方便起见收集到一个数组中),将它们变为大写,然后将它们放回字符串中:
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)
在 GraphQL 中,您可以编写如下内容来定义查询:
const USER_QUERY = gql`
{
user(id: 2) {
name
}
}
`
在样式组件中,您可以像这样定义样式组件:
const Button = styled.button`
background-color: papayawhip;
`
这是什么语法?我知道使用模板文字可以使用以下语法子变量:${foo}
但我从未见过这种用法。任何指导将不胜感激。
模板文字有一个附加功能,称为标记模板。这就是开始反引号之前的前缀。前缀实际上是一个函数的名称 - 该函数被传递给模板字符串的常量部分和内插值(${}
部分中的内容)并且可以将结果字符串处理成它想要的任何东西(尽管通常是另一个字符串,不一定是)。
有关标记模板如何工作的更多详细信息,请参阅 this page on MDN。
这些是tagged template literals。背包之前的部分是对将调用以处理字符串的函数的引用。
函数将变量(${}
部分)作为参数以及围绕变量的字符串片段传递到一个数组中。函数的 return 值成为模板的值。由于这种非常通用的格式,您几乎可以使用该函数做任何事情。这是一个快速而肮脏的示例,它获取变量(为方便起见收集到一个数组中),将它们变为大写,然后将它们放回字符串中:
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)