如何在React饼图中显示图例旁边的值?收到“未定义”错误

问题描述 投票:0回答:1

我试图在图例旁边显示值,但我没有定义。 已调试,但没有成功,您可以告诉我如何修复它吗?

在下面提供我的代码片段和 stackblitz

https://stackblitz.com/edit/react-piechart-padding-complete-8jdttg?file=index.js

status_pie_data: [
  // {"name":"On Arrival","value":0},
  { name: 'Daily', value: 100 },
  { name: 'Weekly', value: 20 },
  { name: 'Monthly', value: 30 },
  { name: 'One Time', value: 50 },
  // {"name":"Active","value":0},
  // {"name":"Completed","value":0}
],

<Legend
            layout="vertical"
            verticalAlign="middle"
            align="right"
            wrapperStyle={{
              fontFamily: 'Lato',
              fontWeight: 400,
              fontColor: '#000',
              fontSize: '9pt',
              marginRight: '0px',
            }}
            formatter={(value, entry, index) => `${entry.name}: ${value}`} // Customize formatter
javascript reactjs legend pie-chart
1个回答
0
投票

为了实现它,您需要使用 content 属性。 prop 需要返回 JSX 元素(可以是数组)。我们将使用 map 循环访问有效负载,然后渲染我们需要的值:

           <Legend
            layout="vertical"
            verticalAlign="middle"
            align="right"
            wrapperStyle={{
              fontFamily: 'Lato',
              fontWeight: 400,
              fontColor: '#000',
              fontSize: '9pt',
              marginRight: '0px',
            }}
            content={(obj) =>
              obj.payload.map((item) => (
                <div>
                  {item.value}: {item.payload.value}
                </div>
              ))
            }
          />

要了解您在内容对象中获得的更多信息,您可以控制台记录它。

如果您通过控制台记录 obj.payload 中的每个项目,您将看到:

color: "#ffb2b2"
payload: Object
type: "rect"
value: "One Time"

并且 item.payload 是:

cornerRadius: undefined
cx: 125
cy: 125
endAngle: 360
fill: "#ffb2b2"
innerRadius: 50
maxRadius: 169.7056274847714
midAngle: 315
middleRadius: 73
name: "One Time"
outerRadius: 96
paddingAngle: 0
payload: Object
percent: 0.25
startAngle: 270
stroke: "#ffffff"
strokeLinecap: "round"
strokeWidth: "5px"
tooltipPayload: Array[1]
tooltipPosition: Object
value: 50
© www.soinside.com 2019 - 2024. All rights reserved.