【问题标题】:Props conditional rendering using styled-components使用 styled-components 进行条件渲染
【发布时间】:2020-08-21 10:09:05
【问题描述】:

我在 React 应用程序中使用 styled-components 库,我有这个块,例如:

const Wrapper = styled.div`
  background: red;
`;

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

const Wrapper = styled.div`
  background: red;
  color: white; // color should be added only if this.props.myProps == 'ok'
`;

最好的方法是什么?

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

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

    const Wrapper = styled.div(
      (props) => css`
        background: red;
    
        ${props.isOK &&
        css`
          background-color: black;
          color: white;
        `}
      `
    );
    

    【讨论】:

      【解决方案2】:

      对于一种风格:

      const Wrapper = styled.div`
          background: red;
          color: ${props => props.myProps === 'ok' && 'white'};
      `;
      

      对于多种样式:

      const Wrapper = styled.div`
          background: red;
          ${props => {
              if (props.myProps === 'ok') return `
                  background-color: black;
                  color: white;
              `
          }}
      `;
      

      另一种选择是使用styled.css:

      // Define a pure group of css properties
      const okStyle = styled.css`
          background-color: black;
          color: white;
      `;
      
      // Reuse okStyle inside a styled component
      const Wrapper = styled.div`
          background: red;
          ${props => props.myProps === 'ok' && okStyle}
      `;
      

      【讨论】:

      • 如果我的道具是 != 'ok' 怎么办? color 会被添加到 CSS 中吗?有不同的方法吗?我需要添加的不仅仅是color
      • color 将为空,所以没有变化
      • 我用多种样式的代码更新了我的答案
      • 您尝试了我的哪一种解决方案? 1、2 还是 3?
      • 同时在package.json 文件中检查您的styled-components 版本。当前版本是5.1.0
      【解决方案3】:

      你应该添加

      const Wrapper = styled.div`
        background: red;
        color: ${p => p.isOk ? 'white' : 'green'}; // color will be added only if this.props.myProps == 'ok', else color will be green
      `;
      

      要发送这个道具,你应该使用像

      这样的语法
      return (
        <Wrapper isOk={true}>Some text</Wrapper>
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-19
        • 2021-10-30
        • 2020-07-20
        • 1970-01-01
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        • 2021-07-16
        相关资源
        最近更新 更多