我正在使用样式组件,并使用其标记的模板文字语法生成组件,例如:
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)} } `}));
是否可以同时传递一个值和一个标记的模板文字,还是我用这种错误的方式?
标记的模板文字不是魔术,您只需要从media(12)调用中返回另一个函数:
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 `)