首页 > 解决方案 > 如何在 React 中悬停时转换背景图像

问题描述

我的意图是在用户鼠标进入 1.5 倍时将背景图像缩放,但我的尝试证明失败了。这是我的代码:

import React from 'react';
import Slider from './index';
import horizontalCss from './css/horizontal.scss';
import content from './content';
import SourceView from './SourceView';
import './css/styles.scss';

function Autoplay() {
	return (
		<div>
			
			<Slider classNames={horizontalCss} autoplay={3000}>
				{content.map((item, index) => (
					<div
						key={index}

						style={{ background: `url('${item.image}') no-repeat center center`, 
                           '&:hover': {
							background: 'white',
							transform: 'scale(1.5)',
							}, }}
					>
						<div className="center">
							<div className="textWrapper">
							<h2>{item.title}</h2>
							</div>
						</div>
					</div>
				))}
			</Slider>
			
		</div>
	);
}

export default Autoplay;

我必须做哪些调整才能完成这项工作

标签: javascriptcssreactjs

解决方案


正如人们之前提到的,这不是 React 的问题。相反,HTML 中的 style 属性不支持 CSS 选择器,例如:hover. 另请注意,这&:hover不是有效的 CSS,而是由您选择的 webpacker 预处理的有效 SCSS。

但是,您的特定悬停样式<div>不会对任何内容做出反应,因此可以将它们放在一个类中

.my-image-class {
  background-repeat: no-repeat;
  background-position: center;

  &:hover {
    background: white;
    transform: scale(1.5);
  }
}

然后你可以在不悬停时切换背景图像

<div
  key={index}
  className="my-image-class"
  style={{ background: `url('${item.image}') }} 
>

奖励:您可能会想更进一步,并且想让您悬停图像反应,这种策略会失败。Kalabasa有一个很好的答案,它使用动态 CSS 变量(MDN 文档)作为反应类属性。

你可以像这样在课堂上陈述你的背景:

.my-image-class {
  background-image: var(--my-image);
  background-repeat: no-repeat;
  background-position: center;

  &:hover {
  background-image: var(--hover-image);
    transform: scale(1.5);
  }
}

然后动态改变变量

<div
  key={index}
  className="my-image-class"
  style={{ '--my-image': `url(path)`; '--hover-image': `url(other-path)` }} 
>

推荐阅读