javascript - 在 React Js 中更改图像 onClick

标签 javascript reactjs image react-hooks toggle

我正在尝试在我的 React Js 项目中创建一个页面,内容位于左侧,内容的图像位于右侧。到目前为止,我已经能够创建一个根据所选标题更改文本和图像的切换功能,因此,例如,如果用户单击标题 1,将显示 text1 和 image1,当用户单击 title2 时,将显示 text2 和image2 将被渲染等等。问题是在单击标题之前图像不会加载,但是我需要在第一次加载页面时显示 img1(然后 img1 应该更改为 img2 或 img3,具体取决于单击的标题)。

codesandbox

我的代码:

import React, { useState } from "react";
import "./styles.css";

const data = [
  {
    id: "1",
    key: "1",
    title: "Title1",
    text: "Text1.",
    img: "1.jpg"
  },
  {
    id: "2",
    key: "2",
    title: "Title2",
    text: "Text2.",
    img: "2.jpg"
  },
  {
    id: "3",
    key: "3",
    title: "Title3",
    text: "Text3.",
    img: "3.jpg"
  },
  {
    id: "4",
    key: "4",
    title: "Title4",
    text: "Text4",
    img: "4.jpg"
  }
];

export default function App() {
  const [toggled, toggle] = useState("");
  return (
    <div className="App">
      {data.map(({ title, text, key, img }) => {
        return (
          <>
            <div className="main">
              <div className="text">
                <h1 onClick={() => toggle(key)}>{title} </h1>
                {toggled === key ? (
                  <>
                    <p>{text}</p>
                  </>
                ) : null}
              </div>

              <div className="img">
                {toggled === key ? (
                  <>
                    <img src={img} key={key} className="photo" />
                  </>
                ) : null}
              </div>
            </div>
          </>
        );
      })}
    </div>
  );
}

这是页面现在加载时的显示方式

how it's now

这就是我希望页面加载的方式(显示 img1)

how I want it

我想做的是当页面加载时,它应该显示 img1,但是当用户单击 title2 时,img1 应该更改为 img2,任何建议将不胜感激,

谢谢。

最佳答案

我为你做了一些重构,试试这个:https://codesandbox.io/s/toggle-kc3q2

我将初始状态设置为“1”,并使用 togglesetToggle 作为状态和状态 setter

关于javascript - 在 React Js 中更改图像 onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62421700/

相关文章:

css - React JS 中的悬挂缩进

reactjs - 使用 Definitely Typed 中的 Typescript 定义文件和旧版本的 Typescript

Python:如何使用 PyQt 调整光栅图像的大小

asp.net - 如何在 ASP.NET 应用程序中有效地缩放和裁剪图像?

javascript - 从 jQuery 日期选择器获取查询值(格式问题)

javascript - 如何引用这个预加载的图像

javascript - 在 PHP 中的 AJAX post 上获取空值

android - ReactJS 与原生 Android 中的 Webview 通信 ('Android' 未定义 no-undef)

javascript - Skrollr 图像闪烁。 Firefox 预加载问题

javascript - 如何处理 passport.deserializeUser() 中的错误?