样式化的组件 css 助手不与 mixin 一起工作

Styled component css helper not working with mixin

我想根据传递的道具更改 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>
    </>
  );
};

这种复杂的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}
`;

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

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

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

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