首页 > 解决方案 > React Native 中的树形图形状并不完美(d3,react-native-svg)

问题描述

我想在 react native 中显示树形图,我找到了这个博客。我试图在本机反应中实现它,它可以工作,但形状并不完美。我也尝试过做出反应,效果很好,形状也很完美。样本

谁能让我知道我在 react native 中错过了什么?

反应原生的树形图

反应本机代码:

import React from 'react'
import { Dimensions } from 'react-native'
import * as d3 from 'd3'
import * as SvgC from 'react-native-svg'
import { SafeAreaView } from 'react-native-safe-area-context'
const { Rect, G, Svg } = SvgC

interface Props {
  data: any
}

const TreeMap = ({ data }: Props) => {
  const windowWidth = Dimensions.get('window').width
  const windowHeight = Dimensions.get('window').height

  const root = d3
    .hierarchy(data)
    .sum((d) => d.value)
    .sort((a, b) => b.value - a.value)
  const treemapRoot = d3
    .treemap()
    .size([windowWidth, windowHeight])
    .padding(1)(root)

  const fader = (color) => d3.interpolateRgb(color, '#fff')(0.3)
  const colorScale = d3.scaleOrdinal(
    d3.schemeCategory10.map(fader)
  )
  return (
    <SafeAreaView>
      <Svg
        height={windowHeight}
        width={windowWidth}
        viewBox={`0 0 ${windowWidth} ${windowHeight}`}
      >
        {treemapRoot.leaves().map((leave) => {
          return (
            <G
              transform={`translate(${leave.x0},${leave.y0}`}
              onPress={() => console.log('hello')}
            >
              <Rect
                width={leave.x1 - leave.x0}
                height={leave.y1 - leave.y0}
                fill={colorScale(leave.data.category)}
              />
            </G>
          )
        })}
      </Svg>
    </SafeAreaView>
  )
}

export default TreeMap

标签: react-natived3.jsreact-native-svg

解决方案


错过了矩形 x 和 y 位置。

              <Rect
                x={leave.x0}
                y={leave.y0}
                width={leave.x1 - leave.x0}
                height={leave.y1 - leave.y0}
                fill={colorScale(leave.data.category)}
              />

在此处输入图像描述


推荐阅读