使用样式组件进行道具条件渲染

ale*_*e91 2 reactjs styled-components

我在 React 应用程序中使用样式组件库,例如我有这个块:

const Wrapper = styled.div`
  background: red;
`;
Run Code Online (Sandbox Code Playgroud)

如果道具有设定值,我需要添加一些其他样式,例如:

const Wrapper = styled.div`
  background: red;
  color: white; // color should be added only if this.props.myProps == 'ok'
`;
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

Gol*_*Jer 8

另一个语法选项。
这实际上就是我现在编写所有样式组件的方式。它使迭代/更新变得更容易。

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

const Wrapper = styled.div(
  (props) => css`
    background: red;

    ${props.isOK &&
    css`
      background-color: black;
      color: white;
    `}
  `
);
Run Code Online (Sandbox Code Playgroud)

  • 从“styled-components”导入 styled, { css }; (4认同)