【问题标题】:Styled component css helper not working with mixin样式化的组件 css 助手不能与 mixin 一起使用
【发布时间】:2022-01-25 08:38:58
【问题描述】:

我想改变 StyledButton 取决于传递的道具。当complex 为true 时,它应该去complexMixin 然后确定whiteColor 传递的内容。但即使我用true 传递whiteColor,颜色也是黑色,而不是白色。

有人知道这是怎么回事吗?谢谢!

Demo

import styled, { css } from "styled-components";

const complexMixin = css`
  color: ${({ whiteColor }) => (whiteColor ? "white" : "black")};
`;

const StyledButton = styled.div`
  border: 1px solid red;
  height: 100px;
  text-align: center;
  margin: 20px;
  font-weight: 700;
  font-size: 40px;
  color: ${({ complex }) => (complex ? complexMixin : "green")};
`;

const App = () => {
  const isComplex = true;
  const isWhite = true;
  return (
    <>
      <StyledButton whiteColor={isWhite} complex={isComplex}>
        ccc
      </StyledButton>
      <StyledButton complex={!isComplex}>BBB</StyledButton>
    </>
  );
};

【问题讨论】:

    标签: styled-components react-props


    【解决方案1】:

    通常,我会这样写这种复杂的 CSS 逻辑。

    const complexMixin = css`
      ${({ complex, whiteColor }) =>
        complex &&
        css`
          color: #000;
          ${whiteColor &&
          css`
            color: #fff;
          `}
        `}
      ${({ complex }) =>
        !complex &&
        css`
          color: green;
        `}
    `;
    
    const StyledButton = styled.div`
      border: 1px solid red;
      height: 100px;
      text-align: center;
      margin: 20px;
      font-weight: 700;
      font-size: 40px;
      ${complexMixin}
    `;
    

    【讨论】:

      【解决方案2】:

      对于你的 mixin,你可以这样做:

      const complexMixin = ({ whiteColor }) => whiteColor ? "white" : "black";
      

      color: ${({ complex }) => (complex ? complexMixin : "green")};
      

      在您的代码中,我们看到您想在另一个“颜色:”中添加一个“颜色:”

      【讨论】:

        猜你喜欢
        • 2018-03-17
        • 2019-11-16
        • 2017-09-19
        • 2023-01-18
        • 2017-12-13
        • 2019-04-21
        • 2012-10-08
        • 2019-09-01
        • 2018-10-17
        相关资源
        最近更新 更多