【问题标题】:How do I create an overlay in React?如何在 React 中创建叠加层?
【发布时间】:2021-12-29 03:13:53
【问题描述】:

我目前正在尝试在悬停时在图像上创建叠加层。我可以在屏幕上显示一个框,但它没有放在图像上。

featured.js

const Featured = ({ images }) => {
  if (!images || !Array.isArray(images)) return null;

  return (
    <section className={styles.featuredWrapper} id="work">
      {images.map((image) => {
        return (
          <div className={styles.wrap}>
            <GatsbyImage
              image={image.gatsbyImageData}
              alt="Link to the alt text"
              className={styles.featuredImg}
            />
            <div className={styles.featuredOverlay}>Test</div>
          </div>
        );
      })}
    </section>
  );
};

featured.module.css

.featuredImg {
  width: 100%;
  position: relative;
}

.featuredOverlay {
  position: absolute;
  background: black;
  opacity: 0.5;
  width: 100%;
  height: 100%;
  z-index: 1;
}

我看到的每一个解释都围绕着绝对和相对位置的使用,这让我认为我的问题是我如何渲染我的组件。我是否在错误的元素上使用了位置属性?

【问题讨论】:

  • 您可能希望在数组映射内的外部 div 中添加一个键。此外,创建叠加层的更简单方法是让图像的父级保留叠加层颜色,然后在悬停时更改图像的不透明度。
  • 为什么不设置图片的宽度呢?另外,您是否为父 div styles.wrap 设置了 position?尝试在styles.wrap 上将position 设置为相对或绝对。
  • 您需要父 div 是相对位置,以便在绝对定位时覆盖以填充它

标签: javascript html css reactjs


【解决方案1】:
import { useState } from "react";
import "./styles.css";

function Home() {
  const [showOverlay, setShowOverlay] = useState(false);

  return (
    <div>
      <div className="main-container">
        <div className="main-container__grid">
          <img
            src="https://miro.medium.com/max/2000/1*3SjDVyFY09xZ7NYMO5kj0g.png"
            className="test"
            alt="Placeholder"
            onHover={() => setShowOverlay(true)}
          />
          {showOverlay && <div className="targeting-box" />}
        </div>
      </div>
    </div>
  );
}

export default Home;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    相关资源
    最近更新 更多