样式组件的属性选择器

Attribute Selectors for styled-componnets

在使用 sytled-components 时是否可以使用属性选择器?

&:hover, &[active='true']{
  transform: translateY(-4px);
  box-shadow: 0 7px 16px 0px rgba(255,63,23,0.87),
}

想法是,然后我有以下内容

<Button active />

否则我必须复制代码,它会变得更丑陋。

我会使用 css 助手和一些插值来避免重复代码:

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

const hoverStyles = css`
  transform: translateY(-4px);
  box-shadow: 0 7px 16px 0px rgba(255,63,23,0.87);
`;

const Component = styled.div`
  // If the component is hovered add the hoveredStyles
  &:hover { ${hoverStyles} }
  // If the active property is set add the hoverStyles
  ${props => props.active && hoverStyles}
`

我们不打算像您的代码想法中那样使用属性选择器和道具实现任何特殊行为。我们希望尽可能避免偏离实际 CSS,以避免混淆、highlighting/parsing 问题等

许多您可能想在 CSS 字符串中添加特殊魔法语法的东西都可以通过触摸 JavaScript 实现! (见上文)