【问题标题】:How will we add css property to the class in styled component?我们如何将 css 属性添加到样式组件中的类?
【发布时间】:2020-01-27 11:54:16
【问题描述】:

我对使用 styled-components 设置 react 组件的样式有疑问。使用 styled-component 向按钮添加 css 属性非常容易,如下所示

const Button = styled.button`
      background: black;
      color: white;
      border-radius: 7px;
      padding: 20px;
      margin: 10px;
      font-size: 16px;
      :disabled {
        opacity: 0.4;
      }
      :hover {
        box-shadow: 0 0 10px yellow;
      }
    `;

但是当我们查看元素样式的传统方式时,我陷入了困境。假设我们有按钮,并且我添加了活动类和 css 属性,如下所示

<button class='active'> click me</button>
.active{
   background: red;
   color: black;
}

我们将如何在样式化组件中实现上述样式化元素的方式。目前面临的问题是在点击按钮时动态添加类名,我必须通过样式化组件使用“活动”类名突出显示活动按钮。

【问题讨论】:

    标签: css reactjs sass react-hooks styled-components


    【解决方案1】:

    您可以检查样式组件内的活动道具。在那里,您可以像这样添加基于此道具的样式;

    const Button = styled.button`
      background: black;
      color: white;
      border-radius: 7px;
      padding: 20px;
      margin: 10px;
      font-size: 16px;
      :disabled {
        opacity: 0.4;
      }
      :hover {
        box-shadow: 0 0 10px yellow;
      }
    
      ${props => props.active && `
        /* only show this styling when active*/
        background: red;
        color: black;
      `}
    `
    

    那么你就可以像这样“激活”active了;

    <Button active>click me</Button>
    <Button active={true}>click me</Button>
    

    然后像这样“取消激活”活动;

    <Button>click me</Button>
    <Button active={false}>click me</Button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-30
      • 2019-01-29
      • 2016-02-23
      • 1970-01-01
      • 2021-07-02
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多