【问题标题】:How to pass marginBottom to a styled component?如何将 marginBottom 传递给样式化的组件?
【发布时间】:2018-02-22 00:23:33
【问题描述】:

我有以下 ui 组件:

const StyledLabel = styled.div`
  color: ${(props) => props.theme.colors.black};
`;

const Label = ({
  text,
  marginBottom,
}) => (
  <StyledLabel
    style={{ marginBottom }}
  >
    {text}
  </StyledLabel>
);

我想要做的是删除样式属性并让样式组件处理边距底部......所以我现在有:

const StyledLabel = styled.div`
  color: ${(props) => props.theme.colors.black};
  margin-bottom: ${(props) => props.marginBottom};
`;

const Label = ({
  text,
  marginBottom,
}) => (
  <StyledLabel
    marginBottom={marginBottom}
  >
    {text}
  </StyledLabel>
);

上面的问题是应用于元素的 CSS 是:

margin-bottom: 8;

不是想要的8px -- 我可以让样式组件像style 那样神奇地添加px 吗?或者我是否需要更新我的应用程序,从通过 marginBottom 88px

【问题讨论】:

  • 你能把StyledLabel改成追加px,比如const StyledLabel = styled.div` color: ${(props) =&gt; props.theme.colors.black};margin-bottom: ${(props) =&gt; props.marginBottom + 'px'}; `;

标签: reactjs styled-components


【解决方案1】:

嘿,伙计,为什么要将css 规则与组件混合,我认为您可以发送不同的className 并在file.css 中创建css 规则,这样会更容易管理。但是,如果您想继续使用您的代码,您只需添加 px

margin-bottom: {${props.marginBottom}px`};

或者您可以创建一个const 并在之后添加它。

【讨论】:

    猜你喜欢
    • 2019-04-30
    • 2019-07-25
    • 2019-06-26
    • 2019-05-17
    • 2019-09-23
    • 2020-10-30
    • 2020-10-28
    • 2020-04-10
    • 2020-06-06
    相关资源
    最近更新 更多