首页 > 解决方案 > 如何使按钮在ReactJS中鼠标悬停在图像上

问题描述

我在 ReactJS 中有一个使用引导程序的图像库。我想添加按钮来删除或进一步修改图像。当鼠标悬停在相应的图像上时,这些按钮应该只出现在图像的角落。我一直在广泛地寻找,要么我只是不知道这被称为什么的正确术语,要么它不像我想象的那么普遍。当然,如果已经回答了相同的问题,我将非常感谢指出该问题。

标签: reactjsreact-bootstrap

解决方案


您可能会从以下内容开始(基于一张图片):

import React, { useState } from "react";
import { Image, Button } from "react-bootstrap";

const ImageExample = () => {
  const [isHovered, setHover] = useState(false);

  return (
    <div
      className="imageContainer"
      onMouseOver={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
      <Image src="https://via.placeholder.com/150"/>
      {isHovered && (
        <Button
          size="sm"
          style={{
            position: "absolute",
            top: "5px",
            right: "5px",
          }}
          variant="primary"
        >
          Show on hover
        </Button>
      )}
    </div>
  );
};

export default ImageExample;
.imageContainer {
  max-width: 150px;
  max-height: 150px;
  position: relative;
}

沙盒:https ://codesandbox.io/s/zen-wilbur-qugei


推荐阅读