我正在尝试在我的 React Js 项目中创建一个页面,内容位于左侧,内容的图像位于右侧。到目前为止,我已经能够创建一个根据所选标题更改文本和图像的切换功能,因此,例如,如果用户单击标题 1,将显示 text1 和 image1,当用户单击 title2 时,将显示 text2 和image2 将被渲染等等。问题是在单击标题之前图像不会加载,但是我需要在第一次加载页面时显示 img1(然后 img1 应该更改为 img2 或 img3,具体取决于单击的标题)。
我的代码:
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”,并使用 toggle
和 setToggle
作为状态和状态 setter
关于javascript - 在 React Js 中更改图像 onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62421700/