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

时间:2019-12-05 16:17:54

标签: javascript reactjs styled-components css-in-js

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

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 {
     ......
   }
`;

4 个答案:

答案 0 :(得分:3)

使用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'));

Edit zen-https-5bkm5

答案 1 :(得分:1)

您可以使用一个函数并基于prop返回CSS:

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

答案 2 :(得分:0)

替代方法是

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 */
  })

答案 3 :(得分:0)

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

# Method 1 - Using lubridate days() ----------------------------------------

as.POSIXct("2019-05-30 02:00:38", tz = "UTC", format = "%Y-%m-%d %H:%M:%OS") - days(60)
# "2019-03-31 02:00:38 UTC"

# Method 2 - Using base R difftime() ----------------------------------------

as.POSIXct("2019-05-30 02:00:38", tz = "UTC", format = "%Y-%m-%d %H:%M:%OS") - as.difftime(60, unit="days")
# "2019-03-31 02:00:38 UTC"