我有一个JSON数组,其中包含一些带有图像数组的对象和一些带有单个图像的对象.例如:
[
{
"title": "Title",
"img_src": "example.png"
},
{
"title": "Title2",
"img_count": 2,
"img_src": [
"example2.png",
"example3.png"
]
},
{
"title": "Title3",
"img_src": "example4.png"
},
{
"title": "Title4",
"img_count": 3,
"img_src": [
"example5.png",
"example6.png",
"example7.png"
]
}
]
现在,我在两个按钮之间显示图像,如何通过这些按钮更改特定对象(从JSON检索)的图像?
这就是我所做的:
export default function Products({ jsonArr }) {
const [counter, setCounter] = useState(0);
function toggleImage(index) {
setCounter(counter === 0 ? 1 : 0); //This is just for testing.
}
.........
........
<div className="parentElement">
{jsonArr.map((arrEl, i, _) => {
return (
<div key={`${i}`} className="row" style={{ marginBottom: "50px" }}>
<div className="col-sm-4">
{arrEl.img_count && (
<button onClick={() => toggleImage(i)}>
<iconify-icon icon="ep:arrow-left-bold"></iconify-icon>
</button>
)}
{arrEl.img_count ? (
<img key={arrEl.title} src={arrEl.img_src[counter]} className="cover" height="250" width="250" alt="products"></img>
) : (
<img key={arrEl.title} src={arrEl.img_src} className="cover" height="250" width="250" alt="products"></img>
)}
{arrEl.img_count && (
<button onClick={() => toggleImage(i)}>
<iconify-icon icon="ep:arrow-right-bold"></iconify-icon>
</button>
)}
</div>
...more code here...
我只在对象中存在'img_count'时才显示按钮."toggleImage"按钮功能正在工作,但它正在更改数组中所有对象的图像.
请建议一些更好的方法来做到这一点.或者这一点是否可以纠正.