我正在使用styled-components并使用其标记的模板文字语法生成组件,例如:
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)}
}
`}));
是否可以传递值和标记模板文字,或者我是以错误的方式进行此操作?
答案 0 :(得分:3)
Tagged template literals不是魔术,你只需要从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
`)