简体   繁体   English

防止在动态创建的元素上发生 onClick 事件

[英]Prevent onClick event on dynamically created elements

I'am fetching data from a database table into my react app.我正在从数据库表中获取数据到我的反应应用程序中。 With the elements from the table I render dynamically buttons and this buttons should have a onClick event.使用表格中的元素,我动态呈现按钮,并且该按钮应该具有onClick事件。 Because of the map function the onClick event is fired as often as elements are stored in the database table.由于 map function onClick 事件的触发频率与元素存储在数据库表中的频率一样高。 So my question is if it is possible to prevent the firing of onClick at dynamically creation?所以我的问题是是否可以在动态创建时阻止 onClick 的触发?

//GET request with axios
const getColorHandler = () => {
    httpInstance
        .get("/api/color")
        .then(res => {
            console.log(res.data);
            setColorData(res.data);
        }).catch(err => {
            setColorData(null);
            console.log(err);
        })
};

//JSX
return(
    <section className="uk-flex">
        {colorData.map(color=> (
            <div className="uk-flex-row" key={color.id}>
                <div onClick={setColorHandler(color.type, color.price)}
                     className={
                            (color.id === 1 ? "greyColor" : "") ||
                            (color.id === 2 ? "redColor" : "") ||
                            (color.id === 3 ? "blueColor" : "") ||
                            (color.id === 4 ? "greenColor" : "")
                     }
                ></div>  
            </div>
        ))}
    </section>
);

Your use of onClick si fired immediately, as you've experienced.正如您所经历的,您对 onClick si 的使用立即触发。 If you want to use true onClick event, then you have to have your event this way:如果您想使用真正的onClick事件,那么您必须以这种方式进行事件:

<div onClick={() => setColorHandler(color.type, color.price)}

Or, if you woudl want to use event information:或者,如果您想使用event信息:

<div onClick={(e) => setColorHandler(color.type, color.price)}

Small under the line notice: using clickable <div> is antipattern, you could have aria accessibility issues.小行通知下:使用可点击<div>是反模式,您可能会遇到 aria 可访问性问题。 Better use <button> element.更好地使用<button>元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM