样式组件内部的迭代 [英] Iterations inside of styled components
问题描述
我有一个看起来像的主题对象:
I've got theme object which looks like:
{
h1: {
color: red
},
h2: {
color: blue
}
}
我想遍历该对象并动态创建样式组件样式定义,例如:
And I would like to iterate through that object and dynamically create styled-component style definitions like:
createGlobalStyle`
${props => Object.keys(props.theme).map(header => {
return css`
${header}: {
color: ${props.theme[header].color;
}
`
}
`
问题是它不起作用:(
您是否知道如何执行诸如遍历对象和动态创建其他标记样式之类的基本操作?
Have you maybe idea how to do so basic stuff like iterating through the object and dynamically create additional tagged styles?
推荐答案
首先,你的 createGlobalStyle
代码示例有点乱,缺少关闭 )
和 }
全部结束.
Firstly your createGlobalStyle
code example is a bit of a mess missing closing )
and }
all over.
其次 Object.keys(props.theme).map(...)
将返回一个 Array
.
Secondly Object.keys(props.theme).map(...)
will return an Array
.
您的目标应该是至少返回一个 模板文字 来自该示例块.
You should be aiming to at least return a Template literal from that example block.
第三,针对标记名的 CSS 类没有用冒号定义:
Thirdly, CSS classes targeting tagnames aren't defined with colons:
${header}: {
color: ${props.theme[header].color;
}
这是一个工作示例:
${({ theme }) => {
let templateLiteral = ``;
Object.keys(theme).forEach(n => {
templateLiteral += `
.${n} {
color: red;
}
`;
});
return templateLiteral;
}}
这篇关于样式组件内部的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!