简体   繁体   中英

How can I make a SVG element clickable on React?

I am using React Native with Expo and I have 4 SVG elements that I need them to be clickable. This is the code for each of these:

  <Svg.G
    id="Passangers-Going-B"
    onPress={() => console.log(`${cardinalPoint} Avatar Was Clicked`)}
   >
...

With that code I am able to click on the SVG element but the weird thing is that when I try to click on another element the click is still firing the event of the last element I clicked on.

I recorded a video with the behavior

So, is there a better way to do this? All I need is to click on those SVG elements in order to change to a new route.

Any ideas?

I am using SVG from expo. import { Svg } from 'expo'; -> https://docs.expo.io/versions/latest/sdk/svg/

I also created a Snack but I don't see it is working at all -> https://snack.expo.io/@maketroli/expo.svg-example?session_id=snack-session-_9YKofW2Y

What I see is that if I click on one of the elements the click gets stuck there because if I click a new element it throws the function of the last clicked element. I have to click around 3 times the new element in order to focus the click on that element.

I saw something about PanResponder but I don't know this has something to do with it.

You should wrap your SVG into a Component that aims only to handle the Press event.

import { TouchableOpacity } from "react-native"

<TouchableOpacity onPress={() => console.log(`${cardinalPoint} Avatar Was Clicked`)}>
    <Svg.G
        id="Passangers-Going-B"
    />
</TouchableOpacity>

You will need to style it appropriatly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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