React中的SVG陷阱

react svg

When we want to use SVG image in React, we may import it like this:

当我们想在React中使用SVG图像时,我们可以这样导入它:

import {ReactComponent as Logo} from "./logo.svg";

In my project, the logo.svg is a X for user to click to delete the item in the list.

在我的项目中, logo.svg是一个X,供用户单击以删除列表中的项目。

I added an onClick function to it as below:

我向它添加了一个onClick函数,如下所示:

图片发布

When we click on the X, the item is undefined. Hence, we can not delete it correctly. However, when we click on the space outside X, but within that square area, it can retrieve the item correctly from the data-item.

当我们单击X时,该itemundefined 。 因此,我们无法正确删除它。 但是,当我们单击X外部但在该正方形区域内的空间时,它可以从数据项中正确检索该项。

The crux of the issue is that we are using event.target which is referencing the actual target that received the click. In this case, the <path> tag. The data-item is on<svg> tag. Therefor, we cannot get the correct data.

问题的症结在于我们正在使用event.target ,它引用的是收到点击的实际目标。 在这种情况下, <path>标记。 data-item位于<svg>标记上。 因此,我们无法获得正确的数据。

It will only happen on SVG graphic as it is a vector graphic defined by a group of paths, boxes, circles, text etc. So, when we clicked on a SVG graphic, we may actually clicked on the paths, boxes, circles, text etc. but not the <svg> itself.

它只会在SVG图形上发生,因为它是由一组路径,框,圆,文本等定义的矢量图形。因此,当我们单击SVG图形时,我们实际上可能单击了路径,框,圆,文本等等,但<svg>本身不行。

图片发布

解: (Solution:)

To solve it, we should use event.currentTarget, which is always the object listening for the event. It always refers to the element to which the event handler has been attached(which is <svg> tag in this case as we added the onClick event handler to it).

为了解决这个问题,我们应该使用event.currentTarget ,它始终是侦听事件的对象。 它始终是指事件处理程序已附加到的元素(在本例中为<svg>标记,因为我们向其中添加了onClick事件处理程序)。

翻译自: https://medium.com/@frankie95/a-small-svg-pitfall-in-react-39cf09a3f66c

react svg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值