样式化组件 - 根据道具有条件地渲染整个 css 块

Styled Components - Conditionally render an entire css block based on props

我了解可以有条件地呈现样式,例如:

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

这看起来并不干 - 我如何(是否可能)根据道具渲染 整个块 css 样式?

类似于:

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

使用 styled-component 或任何 CSS-in-JS,您可以有条件地呈现 css block:

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

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

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

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

完整示例:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import styled, { css } from 'styled-components';

const light = css`
  background-color: white;
  border: 2px solid black;
  color: black;
`;

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

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

const App = () => {
  const [isDark, setIsDark] = useState(false);

  const toggle = () => setIsDark(b => !b);

  return (
    <FlexBox isDark={isDark}>
      <div>Some Text</div>
      <button onClick={toggle}>Change Block</button>
    </FlexBox>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

您可以使用函数和 return css 基于 prop:

const HelloWorldLabel= styled("div")`
  ${({centered}) => {
    if (centered) {
      return `
       display: "block" ;
       margin: "auto 0";
       padding: "0 15px";
      `
    } else {
      return `// Other styles here`
    }
   }}
`;

备选方案是

let customCss = setCustomCss(position) => {
let positionCss = {
center: [ 'css: value;', 'css:value;'],
left: .....
right: ....
}

return   return positionCss[position];

}
  let HelloWorldLabel= styled('div')(customCss, {
    /* css common to all */
  })

一种对我有用的不那么冗长的方法是

const SideMenu = styled.aside`
  width: 200px;
  ${({ isHidden }) => isHidden && `
      display: none;
    `}
  // another random prop you need here
  ${({ redBg }) => redBg && `
    background-color: red;
  `}
`;