在 React Js 中更改图像 onClick

Change image onClick in React Js

我正在尝试在我的 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>
  );
}

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

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

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

谢谢。

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

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

我在这里发布我的解决方案,以防其他人遇到类似问题。我在我的项目中添加了以下代码行:

***const [visible, setVisible] = useState(true);***

<h1 onClick={() => {
setToggle(key);
***setVisible(false);***
}}>

<div className="img">
***{visible && key === "1" ? (
<img src={img} 
key={key}  
/>) 
: null}***
</div>

codesandbox

在这种情况下,加载页面时,它会显示 img1 和仅显示标题(不显示文本),并且只有当用户单击任何标题、文本及其图像时才会显示。