gpt4 book ai didi

javascript - 在 React.js 中,如何遍历 jsx 元素数组并向它们添加属性

转载 作者:行者123 更新时间:2023-12-04 07:18:32 25 4
gpt4 key购买 nike

class TileImages extends React.Component {
render() {
return (
<div className="layout">
<img src={airConditioning} key="air conditioning" alt="air conditioning" />,
<img src={avacado} key="avacado" alt="avacado" />,
<img src={airplane} key="airplane" alt="airplane" />,
<img src={clothes} key="new clothes" alt="new clothes" />
</div>
)
}
}

因此,如果我想为每个 <img> 添加一个“onClick”事件监听器标签,我怎么能这样做?我最好使用常规的 javascript 吗?另外,为每个 <img> 创建单独的 React 组件会更好吗?因为他们每个人都有自己的属性并且必须按照其他图像行事?
我对 React 比较陌生,也是网络开发的业余爱好者,所以如果我的代码和问题没有意义,请多多包涵……
顺便提一句-
如果有人有任何提示,这里是整个代码文件

import React from 'react'

//images
import airConditioning from './images/tiles_0.png'
import avacado from './images/tiles_1.png'
import airplane from './images/tiles_2.png'
import clothes from './images/tiles_3.png'

//CSS styling
import './Images.css'


// const imagesArray = [
// <img src={airConditioning} key="air conditioning" alt="air conditioning" />,
// <img src={avacado} key="avacado" alt="avacado" />,
// <img src={airplane} key="airplane" alt="airplane" />,
// <img src={clothes} key="new clothes" alt="new clothes" />
// ]


export class HomePage extends React.Component {
render() {
return (
<div>
<h1>Lifestyle</h1>
<br />
<TileImages />
</div>
)
}
}




class TileImages extends React.Component {
render() {
return (
<div className="layout">
<img src={airConditioning} key="air conditioning" alt="air conditioning" />,
<img src={avacado} key="avacado" alt="avacado" />,
<img src={airplane} key="airplane" alt="airplane" />,
<img src={clothes} key="new clothes" alt="new clothes" />
</div>
)
}
}



//add classes to react to onClick the image tiles using "react --patterns--"

最佳答案

如果您的所有操作都相同,您可以执行此类操作,为 onClick 添加一个默认函数

const imageProps = [
{ src: airConditioning, key: "air conditioning", alt: "air conditioning"},
{ src: avacado, key: "avacado", alt: "avacado"},
{ src: airplane, key: "airplane", alt: "airplane"},
{ src: clothes, key: "new clothes", alt: "new clothes"}
]

const onAction = (ev) => {
// do something
}

const InteractiveImage = (props) => <img onClick={onAction} {...props} />

const TileImages = () =>
<div className="layout">
{imageProps.map((inputProps) => <InteractiveImage {...inputProps} />)}
</div>
如果您更喜欢保持相同的书写格式,您可以保留语法,但仍将 onclick 函数设置为默认值,直到将其传递给组件,这将覆盖:
const TileImages = () => 
<div className="layout">
<InteractiveImage src={airConditioning} key="air conditioning" alt="air conditioning" />,
<InteractiveImage src={avacado} key="avacado" alt="avacado" />,
<InteractiveImage src={airplane} key="airplane" alt="airplane" />,
<InteractiveImage src={clothes} key="new clothes" alt="new clothes" />
</div>

关于javascript - 在 React.js 中,如何遍历 jsx 元素数组并向它们添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68643827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com