首页 > 解决方案 > 样式化组件 - 具有嵌套类的 css 变量

问题描述

这是代码沙箱的链接 - https://codesandbox.io/s/misty-shadow-lr4tv?file=/src/App.js

知道为什么在模板文字中嵌套 div 不能正常工作吗?我的问题的概述是:

以下是我尝试过/不工作的 3 个示例:

import styled, { css } from 'styled-components/macro'

export const ExampleDiv = styled.div``

/**
 * Option 1
 * Does not work
 */ 
const expandedStyles1 = css`
  ${ExampleDiv} {
    background-color: ${({ theme }) => theme.background.primary};
  }
`

export const Option1 = styled.div<ItemProps>`
  ${({ $isExpanded }) => {
    return `${$isExpanded && expandedStyles1}`
  }}
`

/**
 * Option 2
 * Does work
 */ 
export const Option2 = styled.div<ItemProps>`
  ${({ $isExpanded }) => {
    const expandedStyles2 = `
      ${ExampleDiv} {
        background-color: ${({ theme }) => theme.background.primary};
      }
    `
    return `${$isExpanded && expandedStyles2}`
  }}
`

/**
 * Option 3
 * Does work
 */ 
const expandedStyles3 = `
  ${ExampleDiv} {
    background-color: gree;
  }
`

export const Option3 = styled.div<ItemProps>`
  ${({ $isExpanded }) => {
    return `${$isExpanded && expandedStyles3}`
  }}
`

标签: reactjsnestedstyled-componentstemplate-literals

解决方案


推荐阅读