使用标记的模板文字传递更多参数

IT技术 javascript reactjs ecmascript-6 styled-components
2021-05-16 16:00:07

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

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)}
  }
`}));

是否可以同时传递值和标记的模板文字,或者我是否以错误的方式进行处理?

1个回答

标记的模板文字不是魔术,你只需要从你的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
`)