如何将Victory Native垂直图例渲染在图表右侧并实现50:50分屏
实现方案
你可以通过拆分容器、嵌套滚动组件、使用flex弹性布局来实现需求,具体修改逻辑如下:
- 外层容器设置全屏宽度+水平布局,左右两个子容器各设置
flex:1自动占满50%屏幕宽度,不需要写死固定像素值 - 饼图单独放在左侧容器中,和图例区域分离
- 右侧图例区域嵌套
ScrollView,当分类数量超过容器高度时自动触发滚动,同时将图例排列方向改为竖直适配右侧布局
修改后的完整代码如下:
import { ScrollView, View } from 'react-native'; // 其余Victory相关导入保持原有配置即可 export default () => { const { Layout } = useTheme(); // 公共参数抽离避免重复定义 const colorScale = ["tomato", "lightgreen", "gold", "cyan", "navy", 'teal', 'magenta', 'green', 'orange', 'aqua', 'fuchsia', 'purple']; const chartData = [ { x: "one", y: 35 }, { x: "Two", y: 40 }, { x: "Three", y: 25 }, { x: "four", y: 55 }, { x: "five", y: 55 } ]; return <View style={[Layout.rowCenter, { flex: 1, width: '100%' }]}> {/* 左侧饼图区域 占50%宽度 */} <View style={{ flex: 1 }}> <VictoryContainer height={400} style={{ padding: 10 }}> <VictoryPie height={400} colorScale={colorScale} labels={() => null} data={chartData} /> </VictoryContainer> </View> {/* 右侧图例区域 占50%宽度 支持滚动 */} <ScrollView style={{ flex: 1, maxHeight: 400 }}> <VictoryLegend style={{ labels: { fontSize: 20, fill: "white" } }} gutter={20} orientation="vertical" colorScale={colorScale} data={chartData.map(item => ({ name: item.x }))} /> </ScrollView> </View> }
如果需要适配不同尺寸的设备,可以通过DimensionsAPI获取屏幕宽度动态设置饼图的宽高参数即可。
内容的提问来源于stack exchange,提问作者Pila
相关产品推荐
相关产品推荐

