问题描述
背景: 我正在尝试在本教程之后将工具提示添加到react-native-svg图表。 教程的链接:Link
当前代码实现:
import React,{useState} from 'react';
import {View,Text,Dimensions} from 'react-native';
import {LineChart} from 'react-native-chart-kit';
import {Rect,Text as TextSVG,Svg} from 'react-native-svg';
const Charts = () => {
let [tooltipPos,setTooltipPos] = useState({
x: 0,y: 0,visible: false,value: 0,});
return (
<View>
<LineChart
data={{
labels: ['January','February','march','April','May','June'],datasets: [
{
data: [100,110,90,130,80,103],},],}}
width={Dimensions.get('window').width}
height={250}
yAxisLabel="$"
yAxisSuffix="k"
yAxisInterval={1}
chartConfig={{
backgroundColor: 'white',backgroundGradientFrom: '#fbfbfb',backgroundGradientTo: '#fbfbfb',decimalPlaces: 2,color: (opacity = 1) => `rgba(0,${opacity})`,labelColor: (opacity = 1) => `rgba(0,style: {
borderRadius: 0,propsForDots: {
r: '6',strokeWidth: '0',stroke: '#fbfbfb',}}
bezier
style={{
marginVertical: 8,borderRadius: 6,}}
decorator={() => {
return tooltipPos.visible ? (
<View>
<Svg>
<Rect
x={tooltipPos.x - 15}
y={tooltipPos.y + 10}
width="40"
height="30"
fill="black"
/>
<MaterialCommunityIcons
name="run"
size={32}
color="rgb(67,67,67)"
/>
<TextSVG
x={tooltipPos.x + 5}
y={tooltipPos.y + 30}
fill="white"
fontSize="16"
fontWeight="bold"
textAnchor="middle">
{tooltipPos.value}
</TextSVG>
</Svg>
</View>
) : null;
}}
onDataPointClick={(data) => {
let isSamePoint = tooltipPos.x === data.x && tooltipPos.y === data.y;
isSamePoint
? setTooltipPos((prevIoUsstate) => {
return {
...prevIoUsstate,value: data.value,visible: !prevIoUsstate.visible,};
})
: setTooltipPos({
x: data.x,y: data.y,visible: true,});
}}
/>
</View>
);
};
问题: 我想添加图标(运行图标),如上图所示,位于工具提示文本旁边。 图标,然后将矩形内的文本填充为黑色。当我尝试放置它时,由于某种原因,它会显示在最左上角。如何定位?
解决方法
您可以使用react-native-svg中的ForeignObject
组件,并将decorator
更改为以下内容:
decorator={() => {
return tooltipPos.visible ? (
<ForeignObject x={tooltipPos.x} y={tooltipPos.y}>
<View
style={{
width: 70,flexDirection: 'row',backgroundColor: 'black',}}>
<MaterialCommunityIcons
name="run"
size={32}
color="rgb(67,67,67)"
/>
<Text
style={{
color: 'white',fontSize: 16,fontWeight: 'bold',textAnchor: 'middle',}}>
{tooltipPos.value}
</Text>
</View>
</ForeignObject>
) : null;
}}
您以前遇到的问题是,react-native-svg Text
和Rect
组件使用x
和y
坐标,而您的图标却没有,因此定位将关闭。
上面显示的方法的好处是您只需指定x
的{{1}}和y
道具。 ForeignObject
内部的所有内容都可以是常规视图,其位置通常与您{https://github.com/react-native-community/react-native-svg#foreignobject)一样。
我分别为ForeignObject
的{{1}}和tooltipPos.x
道具值选择了tooltipPos.y
和x
,但是如果
请确保从react-native-svg 导入y
。