Iterations inside of styled components

天涯浪子 提交于 2019-12-11 19:04:50

问题


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

The problem is that it is not working :(

Have you maybe idea how to do so basic stuff like iterating through the object and dynamically create additional tagged styles?


回答1:


Firstly your createGlobalStyle code example is a bit of a mess missing closing ) and } all over.

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.

Thirdly, CSS classes targeting tagnames aren't defined with colons:

${header}: {
    color: ${props.theme[header].color;
}

Here's a working example:

${({ theme }) => {
    let templateLiteral = ``;
    Object.keys(theme).forEach(n => {
        templateLiteral += `
            .${n} {
                color: red;
            }
        `;
    });
    return templateLiteral;
}}


来源:https://stackoverflow.com/questions/53189701/iterations-inside-of-styled-components

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