2017-05-06 61 views
0

使用联合组件时可以使用属性选择器吗?风格化组件的属性选择器

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

的想法是,那么我有以下

<Button active /> 

否则我不得不重复代码,它变得更加丑陋。

回答

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轻松实现! (见上)

+0

谢谢!这就说得通了。我不知道css魔法:) – bernatfortet