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时,该item
是undefined
。 因此,我们无法正确删除它。 但是,当我们单击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