Icône de positionnement en SVG dans React Native

Sep 13 2020

Contexte: j'essaie d'ajouter une info-bulle à un graphique react-native-svg en suivant ce tutoriel. Le lien vers le tutoriel: Lien

Implémentation actuelle du code:

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, 0, 0, ${opacity})`,
          labelColor: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
          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,
                value: data.value,
                y: data.y,
                visible: true,
              });
        }}
      />
    </View>
  );
};

Question: Je veux ajouter l'icône (icône en cours d'exécution) comme indiqué sur l'image ci-dessus, pour être à côté du texte de l'info-bulle. L'icône, puis le texte à l'intérieur du rectangle rempli en noir. Lorsque j'essaie de le positionner, il apparaît à l'extrême gauche pour une raison quelconque. Comment le positionner?

Réponses

1 BasvanderLinden Sep 20 2020 at 15:27

Vous pouvez utiliser le ForeignObjectcomposant de react-native-svg et changer votre decoratoren quelque chose comme ceci:

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;
}}

Le problème avec ce que vous aviez auparavant est que le svg-natif-réactif Textet les Rectcomposants utilisent xet ycoordonnées et pas votre icône, donc le positionnement sera désactivé.

L'avantage de l'approche présentée ci-dessus est que vous n'avez qu'à spécifier les accessoires xet les yaccessoires du ForeignObject. Tout ce qui se trouve à l'intérieur du ForeignObjectpeut être des vues régulières, positionnées comme vous le feriez normalement (https://github.com/react-native-community/react-native-svg#foreignobject).

J'ai choisi les valeurs tooltipPos.xet tooltipPos.ypour les xet yprop de ForeignObjectrespectivement, mais vous pouvez ajouter un décalage si nécessaire.


Assurez-vous d'importer ForeignObjectdepuis react-native-svg .