样式选择器用于样式组件

时间:2017-05-06 20:23:02

标签: styled-components

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

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

我的想法是,我有以下

<Button active />

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

1 个答案:

答案 0 :(得分:1)

我会使用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即可! (见上文)