Victory Native柱状图渲染百分比报错‘yKeys不存在’求助
问题解决:Victory Native XL 柱状图上方显示百分比值
错误原因
你遇到的Property yKeys doesn't exist错误,是因为在<SkiaText>组件中直接引用了yKeys变量,但该变量仅作为<CartesianChart>的props存在,并未在当前作用域中定义。而且即便能访问到,yKeys是数组['percentage'],也不是你需要显示的具体百分比数值。
修复步骤及代码示例
1. 替换错误的文本内容
将<SkiaText>的text属性改为point.yValue,同时可按需格式化数值(比如保留两位小数):
text={point.yValue.toFixed(2)}
2. 定位文本到柱子上方
给<SkiaText>添加x和y属性,基于柱子坐标调整位置,确保文本显示在柱子顶部上方:
x={point.x} y={point.y - 15} // 向上偏移15像素,避免与柱子重叠 textAlign="center"
3. 优化柱子颜色取值
直接使用graphData中自带的color字段,无需依赖外部GRAPH_COLORS数组:
color={graphData[index].color}
完整修正后的代码
const GRAPH_COLORS = [ '#FFD710', '#808000', '#006400', '#708090', '#d62728', '#FF7F50', '#1f88b4', '#9932CC', '#FF4500', '#FFA07A', '#20B2AA', '#00FF7F', '#4682B4', '#FF1493', '#00BFFF', '#FFD700', '#FF69B4', '#8A2BE2', '#FF8C00', ]; const graphData = [{"color": "#FFD710", "percentage": 4.5773, "symbol": "Symbol1"}, {"color": "#808000", "percentage": 5.2791, "symbol": "Symbol2"}] <CartesianChart data={graphData} xKey="symbol" yKeys={['percentage']} domainPadding={{left: 30, right: 30, top: 30, bottom: 20}} axisOptions={{ font, }}> {({points, chartBounds}) => { if (!points) { return null; } return points?.percentage.map((point, index) => { return ( <Bar key={index} chartBounds={chartBounds} points={[point]} animate={{ type: 'spring' }} roundedCorners={{ topLeft: 0, topRight: 0, }} barCount={25} color={graphData[index].color}> <SkiaText color={point.yValue >= 10 ? '#07B419' : '#8B95A1'} font={font} x={point.x} y={point.y - 15} textAlign="center" text={point.yValue.toFixed(2)} /> </Bar> ); }); }} </CartesianChart>
额外说明
toFixed(2)用于将百分比数值保留两位小数,可根据需求调整位数。y={point.y -15}中的偏移量可根据字体大小和图表布局灵活调整,确保文本与柱子间有合适间距。- 若仍想使用
GRAPH_COLORS数组,需确保数组长度与graphData一致,避免索引越界问题。
内容的提问来源于stack exchange,提问作者abcd
相关产品推荐
相关产品推荐

