【问题标题】:how to change a styled component's before content on hover [emotion.js , styled components ]如何在悬停内容之前更改样式组件[emotion.js,样式组件]
【发布时间】:2021-01-24 22:46:33
【问题描述】:

在按钮悬停时我也想更改 :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.135, 0.15, 0.86);
         transform-origin: left center;

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

【问题讨论】:

    标签: reactjs styled-components emotion


    【解决方案1】:

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

    另外,考虑使用模板文字,而不是使用道具的函数。

    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.135, 0.15, 0.86);
        transform-origin: left center;
      }
    
      &:hover {
        color: var(--colorGrey);
    
        &:before {
          content: 'Hovered';
        }
      }
    `;
    

    【讨论】:

    • 非常感谢。我认为这通常遵循 sass 结构对吗?
    • 为什么你说应该使用模板文字而不是函数?那么我该如何访问道具呢?
    • @سعيد 使用 Emotion/Styled 的主要方式是传递模板文字。函数参数用于插值。因此,仅传递一个函数参数,您就错过了模板文字的好处。请注意,在我发送给您的代码中,插值被更新以传递一个接受道具的函数。这通常是使用 Emotion/Styled 进行插值的正确方法。
    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 2019-05-23
    • 2018-07-28
    • 2020-07-09
    • 1970-01-01
    • 2018-05-18
    • 2021-07-13
    • 2018-03-02
    相关资源
    最近更新 更多