Passing further arguments with tagged template literals

青春壹個敷衍的年華 提交于 2019-12-19 17:36:15

问题


I'm working with styled-components and generating components using their tagged template literal syntax such as:

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

In one case I need to call a function that generates a media query based on a breakpoint and passes the tagged template literal of css to be included within.

for example:

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

The media function might look something like this:

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

Is passing both a value and a tagged template literal possible, or am I going about this the wrong way?


回答1:


Tagged template literals are no magic, you just need to return another function from your media(12) call:

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

or using arrow functions

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

to be called as

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

However, if you don't need to do any interpolation but just want to receive a string, it might be easier to write a function with the parameters

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

and call it as

media(12, `
  templateString
`)


来源:https://stackoverflow.com/questions/44825443/passing-further-arguments-with-tagged-template-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!