1

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

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

这个想法是,然后我有以下

<Button active />

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

4

1 回答 1

2

我会使用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,以避免混淆、突出显示/解析问题等。

您可能想在 CSS 字符串中添加特殊的魔术语法的许多事情都可以通过一点 JavaScript 来实现!(往上看)

于 2017-05-07T10:36:13.690 回答