带样式的组件-根据道具有条件地渲染整个CSS块

问题描述 投票:1回答:1

我知道样式可以有条件地呈现,例如:

const HelloWorldLabel= styled("div")<{ centered?: boolean }>`
  display: ${({ centered }) => (centered ? "block" : "flex")};;
  margin: ${({ centered }) => (centered ? "auto 0" : "unset")};
  padding: ${({ centered }) => (centered ? "0 15px" : "unset")};
`;

这看起来不干-我如何(有可能)基于道具渲染CSS样式的entire block

类似:

const HelloWorldLabel= styled("div")<{ centered?: boolean }>`
   if (centered) {
    display: "block" ;
    margin: $"auto 0";
     padding: "0 15px" ;
   } else {
     ......
   }
`;
javascript reactjs semantic-ui styled-components
1个回答
1
投票

使用styled-component或任何CSS-in-JS,您可以有条件地渲染css块:

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

const light = css`
  background-color: white;
  color: black;
`;

const dark = css`
  background-color: black;
  color: white;
`;

const FlexBox = styled.div`
  ${({ isDark }) => (isDark ? light : dark)}
`;

Edit zen-https-5bkm5

© www.soinside.com 2019 - 2024. All rights reserved.