React 中使用 map() 实现点击图片放大功能

心靈之曲
发布: 2025-08-14 16:38:01
原创
699人浏览过

react 中使用 map() 实现点击图片放大功能

本文档旨在帮助开发者理解如何在 React 应用中使用 map() 函数渲染图片列表,并实现点击特定图片后将其放大的功能。我们将探讨两种实现方式:一种是重新创建事件处理函数,另一种是利用 HTML 元素的 data 属性。通过本文,你将掌握如何正确地将索引传递给事件处理函数,从而实现图片放大效果。

方法一:重新创建事件处理函数

当使用 map() 渲染组件列表时,如果需要在点击事件中获取当前元素的索引,一种常见的方法是在 map() 内部重新创建事件处理函数。这样做的好处是可以直接将索引作为参数传递给处理函数。

示例代码:

首先,定义一个状态变量 selectedIndex 用于存储被点击图片的索引:

import React, { useState, useEffect, Fragment } from "react";
import Aos from "aos";
import "aos/dist/aos.css";
import animations from "./data/animations";
import images from "./data/images";
import GridTransf from "./GridTransf";
import nature1 from "../assets/images/DSC00371.JPG";

function Pictures() {
  const [gridIsActive, setGridIsActive] = useState(false);
  const [cardViewIsActive, setCardViewIsActive] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(null); // 新增状态

  useEffect(() => {
    Aos.init({ duration: 1700 });
  }, []);

  const randChoice = (arr) => {
    const randIndex = Math.floor(Math.random() * arr.length);
    return arr[randIndex];
  };

  const transfToGrid = (e) => {
    setGridIsActive(!gridIsActive);
  };

  const openCardView = (e, index) => {
    e.preventDefault();
    setCardViewIsActive(!cardViewIsActive);
    setSelectedIndex(index);
  };

  return (
    <Fragment>
      <button onClick={transfToGrid}>
        <GridTransf />
      </button>
      {!gridIsActive ? (
        <div>
          <h1 className="title-no-grid">Nature 1</h1>
          <img className="picture-img" src={nature1} alt="first image" />
          {images.map((image) => (
            <div>
              <h1 className="title-no-grid">{image.title}</h1>
              <img
                className="picture-img"
                data-aos={randChoice(animations)}
                src={image.image}
                alt="nature1"
              />
            </div>
          ))}
        </div>
      ) : (
        <div className="grid-container">
          <div>
            <h1 className="title-with-grid">Nature 1</h1>
            <img
              className="grid-item picture-img"
              src={nature1}
              alt="first image"
            />
          </div>

          {images.map((image, index) => (
            <button onClick={(e) => openCardView(e, index)}>
              <div className="grid-item">
                <h1 className="title-with-grid">{image.title}</h1>
                <img
                  className="grid-item picture-img"
                  data-aos={randChoice(animations)}
                  src={image.image}
                  alt="nature1"
                />
              </div>
            </button>
          ))}

          {cardViewIsActive && (
            <div className="backdrop" onClick={openCardView}>
              <div className="card-view">
                {selectedIndex !== null && (
                  <img
                    className="grid-item picture-img"
                    src={images[selectedIndex].image}
                    alt={images[selectedIndex].title}
                  />
                )}
              </div>
            </div>
          )}
        </div>
      )}
    </Fragment>
  );
}

export default Pictures;
登录后复制

在这个例子中,openCardView 函数现在接收两个参数:事件对象 e 和当前图片的索引 index。 在 map() 函数中,我们使用箭头函数 (e) => openCardView(e, index) 来创建一个新的函数,并将 index 传递给 openCardView。

注意事项:

  • 这种方法会为每个列表项创建一个新的函数,在列表项数量非常大的情况下,可能会影响性能。

方法二:使用 data 属性

另一种方法是利用 HTML 元素的 data 属性来存储索引。在事件处理函数中,可以通过 e.currentTarget.dataset.index 来获取索引。

析稿Ai写作
析稿Ai写作

科研人的高效工具:AI论文自动生成,十分钟万字,无限大纲规划写作思路。

析稿Ai写作 142
查看详情 析稿Ai写作

示例代码:

import React, { useState, useEffect, Fragment } from "react";
import Aos from "aos";
import "aos/dist/aos.css";
import animations from "./data/animations";
import images from "./data/images";
import GridTransf from "./GridTransf";
import nature1 from "../assets/images/DSC00371.JPG";

function Pictures() {
  const [gridIsActive, setGridIsActive] = useState(false);
  const [cardViewIsActive, setCardViewIsActive] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(null); // 新增状态

  useEffect(() => {
    Aos.init({ duration: 1700 });
  }, []);

  const randChoice = (arr) => {
    const randIndex = Math.floor(Math.random() * arr.length);
    return arr[randIndex];
  };

  const transfToGrid = (e) => {
    setGridIsActive(!gridIsActive);
  };

  const openCardView = (e) => {
    e.preventDefault();
    setCardViewIsActive(!cardViewIsActive);
    setSelectedIndex(+e.currentTarget.dataset.index);
  };

  return (
    <Fragment>
      <button onClick={transfToGrid}>
        <GridTransf />
      </button>
      {!gridIsActive ? (
        <div>
          <h1 className="title-no-grid">Nature 1</h1>
          <img className="picture-img" src={nature1} alt="first image" />
          {images.map((image) => (
            <div>
              <h1 className="title-no-grid">{image.title}</h1>
              <img
                className="picture-img"
                data-aos={randChoice(animations)}
                src={image.image}
                alt="nature1"
              />
            </div>
          ))}
        </div>
      ) : (
        <div className="grid-container">
          <div>
            <h1 className="title-with-grid">Nature 1</h1>
            <img
              className="grid-item picture-img"
              src={nature1}
              alt="first image"
            />
          </div>

          {images.map((image, index) => (
            <button onClick={openCardView} data-index={index}>
              <div className="grid-item">
                <h1 className="title-with-grid">{image.title}</h1>
                <img
                  className="grid-item picture-img"
                  data-aos={randChoice(animations)}
                  src={image.image}
                  alt="nature1"
                />
              </div>
            </button>
          ))}

          {cardViewIsActive && (
            <div className="backdrop" onClick={openCardView}>
              <div className="card-view">
                {selectedIndex !== null && (
                  <img
                    className="grid-item picture-img"
                    src={images[selectedIndex].image}
                    alt={images[selectedIndex].title}
                  />
                )}
              </div>
            </div>
          )}
        </div>
      )}
    </Fragment>
  );
}

export default Pictures;
登录后复制

在这个例子中,我们在 button 元素上添加了 data-index 属性,并将索引 index 赋值给它。 在 openCardView 函数中,我们使用 e.currentTarget.dataset.index 来获取 data-index 的值,并将其转换为数字类型(使用 + 符号)。

注意事项:

  • e.currentTarget 指的是事件绑定的元素(这里是 button),而 e.target 指的是触发事件的元素(可能是 button 内部的子元素)。
  • dataset 对象中的属性名会自动转换为小驼峰命名法,例如 data-index 对应 dataset.index。
  • dataset 中的值都是字符串类型,需要根据需要进行类型转换。

总结

本文介绍了两种在 React 中使用 map() 函数渲染图片列表并实现点击图片放大功能的方法。

  • 重新创建事件处理函数: 简单直接,但可能影响性能。
  • 使用 data 属性: 性能更好,但需要注意 e.currentTarget 和 dataset 的使用。

选择哪种方法取决于具体的应用场景和性能要求。在实际开发中,可以根据需要选择最适合的方法。 希望本文能够帮助你更好地理解如何在 React 中处理列表渲染和事件处理。

以上就是React 中使用 map() 实现点击图片放大功能的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号