我们将如何向样式化组件中的类添加css属性?

我们将如何向样式化组件中的类添加css属性?,css,reactjs,sass,react-hooks,styled-components,Css,Reactjs,Sass,React Hooks,Styled Components,我对使用样式化组件设置react组件的样式表示怀疑。使用样式化组件向按钮添加css属性非常容易,如下所示 const Button = styled.button` background: black; color: white; border-radius: 7px; padding: 20px; margin: 10px; font-size: 16px; :disabled { opacit

我对使用样式化组件设置react组件的样式表示怀疑。使用样式化组件向按钮添加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;
}
点击我
.主动{
背景:红色;
颜色:黑色;
}

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

您可以检查样式化组件中的活动道具。在那里,您可以添加基于此道具的样式,如下所示

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;
  `}
`
然后你可以像这样“激活”活动

<Button active>click me</Button>
<Button active={true}>click me</Button>
<Button>click me</Button>
<Button active={false}>click me</Button>
点击我
点击我
并像这样“去激活”活动

<Button active>click me</Button>
<Button active={true}>click me</Button>
<Button>click me</Button>
<Button active={false}>click me</Button>
点击我
点击我