【问题标题】:Styled components on hover change img src attribute悬停样式组件更改 img src 属性
【发布时间】:2019-03-08 09:34:49
【问题描述】:

我有一个样式组件,如下所示。它是一个 google 社交登录按钮 imgGoogleLogin 是 webpack 加载的路径。

我想在悬停时将 src 属性更改为另一个 src。

有什么方法可以实现吗?非常感谢

const GoogleLoginButton = styled.img.attrs({
  src: imgGoogleLogin,
})`
  width: 190px;
  height: 45px;
  &:hover {
    cursor: pointer;
  }
`;

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    您可以使用纯 CSS 实现此目的:

    通过将您的 img 标签替换为 div 并将其 CSS 设置如下:

    div {
        background: url('to_first_image');
    }
    div:hover {
        background: url('to_second_image');
    }
    

    如果你宁愿保留你的 img 标签并使用一些 JS:

    onHover = (e) => {
      e.setAttribute('src', 'source_to_first_img');
    }
    
    onUnhover = (e) => {
      e.setAttribute('src', 'source_to_second_img');
    }
    

    感谢这个答案:https://stackoverflow.com/a/18032363/10449875

    【讨论】:

    • 谢谢,但如果有人能以样式化组件的方式分享解决方案,将不胜感激
    【解决方案2】:

    我想实现类似的东西,但我发现样式化的组件不能明确地做到这一点。我必须这样做,即创建两个组件,一个是隐藏的,当父级悬停时,我取消隐藏它并隐藏另一个。看起来很老套,但我认为比使用 e.setAttribute 更好。

    const GoogleLoginButton = styled.img.attrs(
            props => ({'src': props.img})
        )`
        display: inline;
        width: 190px;
        height: 45px;
        &:hover {
            cursor: pointer;
        }
    `;
    
    const GoogleLoginButtonHover = styled.img.attrs(
            props => ({'src': props.img})
        )`
        display: none;
        width: 190px;
        height: 45px;
        &:hover {
            cursor: pointer;
        }
    `;
    
    const GoogleLoginButtonParent = styled.div`
        &:hover ${GoogleLoginButtonHover} {
            display: inline;
        }
    
        &:hover ${GoogleLoginButton} {
            display: none;
        }
    `;
    

    在你的渲染中你可以这样使用它:

    <GoogleLoginButtonParent>
        <GoogleLoginButton
            img = {props.img}
        />
        <GoogleLoginButtonHover
            img = {props.imgHover}
        />
    </GoogleLoginButtonParent>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-07
      • 2015-12-22
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      相关资源
      最近更新 更多