有没有办法修改'&:before /:after'来赋予动态属性?

时间:2019-03-26 12:32:53

标签: css reactjs styled-components

一个具有&:before属性的样式化组件,我想授予对动态颜色属性的访问权限。但是我不知道该如何应用。

我已经尝试过将道具传递给 <Hover /> ,并且可以正常工作。但是&:before中的Triangle无法访问它。

const Hover = styled.div`
  padding:7px;
  margin: -102px auto;
  border-style: solid;
  border-radius: 15px; 
  border-width: 3px;
  text-align: left;
  font-weight: 400;
  font-size: 19px;
  color: #000000;
  font-family: sans-serif;
  position: absolute;
  left:-15px;
  z-index:10;

   &:before {
  content: "";
  width: 0px;
  height: 0px;
  position: absolute;
  border-left: 10px solid ;
  border-right: 10px solid transparent;
  border-top: 10px solid ;
  border-bottom: 10px solid transparent;
  left: 19px;
  bottom: -19px;
  z-index:10;

}
`;

作为单个样式组件,以下类是:

class MarkerHover extends Component {

    render() {
        const {color, children}= this.props
        return (


            <Hover style={{backgroundColor: color }}>
           {...children}
                </Hover>


        );
    }
}

export default MarkerHover;

在将颜色道具成功传递到&:before部门之后,我希望有一个完整的彩色窗口。

1 个答案:

答案 0 :(得分:1)

随着样式化组件的文档说明(请参阅https://www.styled-components.com/docs/basics#passed-props),您可以阅读传递的道具:

const Hover = styled.div`
  color: ${props => props.color};
`;

当您像这样传递它们时:

<Hover color="#f00" />

您也可以在伪元素中使用相同的道具:

const Hover = styled.div`
  color: ${props => props.color};
  &::before {
    background: ${props => props.color};
  }
`;

因此,不要在样式化的组件上使用style属性,而要传递常规的道具。

如果只想在特定条件后才应用CSS规则,则可以这样操作:

const Hover = styled.div`
  color: #ccc;
  &::before {
    content: "";
    padding: 16px;
    ${props => props.withBg ? `background-color: ${props.withBg}` : ''}
  }
`;

有背景:

<Hover withBg="#f00" />

无背景:

<Hover />
相关问题