如何在悬停内容之前更改样式组件的[emotion.js,样式组件]

问题描述

在鼠标悬停时,我也想对:before内容进行更改,我在官方文档中找不到答案,我想知道这样做是否可行。 这是我要转换为样式化组件语法的css选择器:

.button:hover::before{}

这是样式化的组件:

import styled from '@emotion/styled'

export const Button =styled.button(props=>{
   return`
    padding: .75rem 2rem ;
    color: #fff;
    background-color: transparent;
    border: 1px solid #000;
    position: relative;
    z-index: 1;
    transition: all .5s cubic-bezier(0.785,0.135,0.15,0.86);
    cursor: pointer;
    width: ${props.width ? props.width:'fit-content'};
    margin-top:  ${props.marginTop ? props.marginTop :0}rem;

    &:before{
         content: '';
         position: absolute;
         z-index: -1;
         height: 100%;
         width: 100%;
         top: 0;
         left: 0;
         ${props.collection?"background-color: #fff;":"background-color: var(--colorGrey);"}
         transition: all .5s cubic-bezier(0.785,0.86);
         transform-origin: left center;

         //I want to change style on hover 
    }
    
    &:hover{
      color:var(--colorGrey);
    }
`})

解决方法

只需将:before伪元素嵌套在:hover伪类中。

另外,考虑使用模板文字,而不是使用支持属性的函数。

import styled from '@emotion/styled';

export const Button = styled.button`
  padding: 0.75rem 2rem;
  color: #fff;
  background-color: transparent;
  border: 1px solid #000;
  position: relative;
  z-index: 1;
  transition: all 0.5s cubic-bezier(0.785,0.135,0.15,0.86);
  cursor: pointer;
  width: ${(props) => (props.width ? props.width : 'fit-content')};
  margin-top: ${(props) => (props.marginTop ? props.marginTop : 0)}rem;

  &:before {
    content: '';
    position: absolute;
    z-index: -1;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    ${(props) => (props.collection ? 'background-color: #fff;' : 'background-color: var(--colorGrey);')}
    transition: all .5s cubic-bezier(0.785,0.86);
    transform-origin: left center;
  }

  &:hover {
    color: var(--colorGrey);

    &:before {
      content: 'Hovered';
    }
  }
`;