【问题标题】:Conditional Check of Props Not Working In Styled-System在样式系统中不工作的道具的条件检查
【发布时间】:2019-10-10 11:23:21
【问题描述】:

我正在尝试使用 Styled-Components 和 Styled-System 创建一个 Button 组件。一般来说,它工作正常。但是,在进行基本的道具测试时,我似乎无法让它发挥作用。

例如,以下代码对我不起作用:

background-color: ${props => (props.bg ? 'red' : 'blue')}

无论我是否设置了bg 属性,背景颜色始终为红色。换句话说,以下组件都返回红色背景:

<Button>Button</Button>
<Button bg="primary.base">Primary</Button>

知道如何有条件地检查是否设置了道具吗?

如果有帮助,我指的是Components 文件夹中的Button.jslayout.js 文件:https://codesandbox.io/s/gatsbystarterdefault-rbzo8?fontsize=14

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    选项 1: 我们确定红色背景是由于 Button.js 文件第 33 行的悬停所致吗?为了确定,将其更改为橙色。

    选项 2:也许您的自定义样式会被您从第 35 行传递到第 44 行的样式覆盖:

      ${borders}
      ${boxShadow}
      ${buttonSize}
      ${fontSize}
      ${height}
      ${lineHeight}
      ${minWidth}
      ${space}
      ${color}
      ${buttonStyle}
    

    在自定义 Button 样式之前先提升该部分,然后重试。

    选项 3: 设置默认蓝色并在属性 bg 存在时覆盖它。为此,请将 Button.js 的第 33 行替换为:

    background-color: blue;
    ${props => props.bg && css`background-color: orange;`}
    

    注意:上述第 33 行中的括号不是必须的:

    背景色:${props => props.bg ? “红色”:“蓝色”}

    【讨论】:

      猜你喜欢
      • 2019-10-31
      • 2019-05-11
      • 2021-12-13
      • 1970-01-01
      • 2020-11-14
      • 2021-08-27
      • 2021-12-31
      • 2021-06-27
      • 2020-10-01
      相关资源
      最近更新 更多