📅  最后修改于: 2023-12-03 15:34:38.656000             🧑  作者: Mango
React Native SVG allows developers to render vector graphics in their applications. With the addition of onPress functionality, users can interact with these SVG elements and trigger actions or navigate to different screens.
To add onPress functionality to an SVG element, wrap it with a Touchable
component and pass in your desired onPress function as a prop. Here's an example:
import React from 'react';
import { View, Text, Touchable, Svg } from 'react-native-svg';
const MySVGComponent = ({ onPress }) => {
return (
<Touchable onPress={onPress}>
<Svg>
{/* Your SVG Elements */}
</Svg>
</Touchable>
);
};
export default MySVGComponent;
In this example, the onPress
prop is passed down from the parent component and will be triggered when the user taps on the SVG element.
Here's an example of how to use onPress with React Native SVG to change the color of a circle:
import React, { useState } from 'react';
import { View, Text, Touchable, Svg, Circle } from 'react-native-svg';
const MySVGComponent = () => {
const [circleColor, setCircleColor] = useState('blue');
const handleCirclePress = () => {
const newColor = circleColor === 'blue' ? 'red' : 'blue';
setCircleColor(newColor);
};
return (
<Touchable onPress={handleCirclePress}>
<Svg width={100} height={100}>
<Circle cx={50} cy={50} r={40} fill={circleColor} />
</Svg>
</Touchable>
);
};
export default MySVGComponent;
The handleCirclePress
function sets the circleColor
state to either blue or red depending on its current value. This state is then used to update the fill
prop of the Circle
component.
With the addition of onPress functionality, React Native SVG becomes an even more powerful tool for creating interactive and visually appealing user interfaces. By wrapping SVG elements with Touchable
components and passing in onPress functions, developers can implement a wide range of user interactions with these vector graphics.