React Native에서 SVG의 위치 지정 아이콘

Sep 13 2020

배경 :이 튜토리얼에 따라 react-native-svg 차트에 툴팁을 추가하려고합니다. 튜토리얼 링크 : 링크

현재 코드 구현 :

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

질문 : 위 이미지와 같이 툴팁 텍스트 옆에 아이콘 (달리기 아이콘)을 추가하고 싶습니다. 아이콘, 사각형 내부의 텍스트가 검정색으로 채워집니다. 위치를 잡으려고 할 때 어떤 이유로 든 맨 왼쪽 상단에 나타납니다. 어떻게 배치합니까?

답변

1 BasvanderLinden Sep 20 2020 at 15:27

ForeignObjectreact-native-svg 의 구성 요소를 사용하고 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및 yprops 만 지정하면된다는 것 ForeignObject입니다. 내부의 모든 항목 ForeignObject은 일반적인 뷰 (https://github.com/react-native-community/react-native-svg#foreignobject).

각각 의 및 소품 값에 대해 tooltipPos.x및 tooltipPos.y을 선택 했지만 필요한 경우 오프셋을 추가 할 수 있습니다.xyForeignObject


ForeignObjectreact-native-svg에서 가져와야 합니다.