10

我正在使用样式化组件并使用其标记的模板文字语法生成组件,例如:

const Button = styled.button`
  background-color: papayawhip;
  border-radius: 3px;
  color: palevioletred;
`

在一种情况下,我需要调用一个函数,该函数基于断点生成媒体查询传递要包含在其中的 css 的标记模板文字。

例如:

media(12)`
   background-color: papayawhip;
`

媒体功能可能看起来像这样:

const media = mapValues(width => ({ css: (...args) => css`
  @media (min-width: ${width}rem) {
    ${css(...args)}
  }
`}));

是否可以同时传递一个值和一个标记的模板文字,或者我是不是走错了路?

4

1 回答 1

5

标记的模板字面量并不神奇,您只需要从media(12)调用中返回另一个函数:

function media(twelve) {
  return function(stringParts, ...interpolationValues) {
    return …
  }
}

或使用箭头函数

const media = (twelve) => (stringParts, ...interpolationValues) => …;

被称为

media(12)`firstPart ${13} secondPart`
// or equvialently
media(12)(["firstPart ", " secondPart"], 13)

但是,如果您不需要进行任何插值,而只是想接收一个字符串,那么使用参数编写一个函数可能会更容易

function media(twelve, string) {
  return …;
}

并将其称为

media(12, `
  templateString
`)
于 2017-06-29T14:10:22.930 回答