首页 > 解决方案 > 如何检查道具以在 Emotion 中的样式对象上输出代码块

问题描述

在 Emotion 中的样式对象上输出代码块的最佳实践是什么?

一个简单的布尔语句如下所示:

const StyledComponent = styled('div')(({ check }) => ({
    position: check ? 'relative' : undefined
})

但是,如果我不想检查每一行代码,那么像下面的示例这样的代码块的最佳解决方案是什么?

const StyledComponent = styled('div')(({ check }) => ({
  // some style here
  // ...

  // only load pseud element if "check" is true
  '&::before': {
    content: `''`,
    position: 'absolute',
    left: '0%',
    top: '0%',
    width: '100%',
    height: '100%',
    background: 'blue'
  }
}))

我有一些解决方案。

标签: emotion-js

解决方案


我想了想并得到了这个解决方案:

const StyledComponent = styled('div')(
  {
    // some style here
    position: 'relative'
  },
  
  ({ check }) =>
    // only load pseudo element if "check" is true
    check
      ? {
          '&::before': {
            content: `''`,
            position: 'absolute',
            left: '0%',
            top: '0%',
            width: '100%',
            height: '100%'
          }
        }
      : undefined
)

推荐阅读