react native实现图表
React Native 图表实现方法
React Native 中实现图表通常需要借助第三方库,以下是几种常见的方法和推荐库:
使用 react-native-chart-kit
react-native-chart-kit 是一个流行的图表库,支持多种图表类型,易于集成。
安装:
npm install react-native-chart-kit
示例代码(折线图):
import { LineChart } from 'react-native-chart-kit';
<LineChart
data={{
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
datasets: [
{
data: [20, 45, 28, 80, 99, 43]
}
]
}}
width={300}
height={220}
yAxisLabel="$"
chartConfig={{
backgroundColor: '#e26a00',
backgroundGradientFrom: '#fb8c00',
backgroundGradientTo: '#ffa726',
decimalPlaces: 2,
color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
}}
/>
使用 victory-native
victory-native 是基于 D3 的 React Native 图表库,功能强大且高度可定制。
安装:
npm install victory-native
示例代码(柱状图):
import { VictoryBar, VictoryChart, VictoryAxis } from 'victory-native';
<VictoryChart>
<VictoryAxis
tickValues={[1, 2, 3, 4]}
tickFormat={['Q1', 'Q2', 'Q3', 'Q4']}
/>
<VictoryAxis
dependentAxis
tickFormat={(x) => (`$${x / 1000}k`)}
/>
<VictoryBar
data={[
{quarter: 1, earnings: 13000},
{quarter: 2, earnings: 16500},
{quarter: 3, earnings: 14250},
{quarter: 4, earnings: 19000}
]}
x="quarter"
y="earnings"
/>
</VictoryChart>
使用 react-native-svg-charts
react-native-svg-charts 基于 SVG,提供高性能的图表渲染。
安装:
npm install react-native-svg react-native-svg-charts
示例代码(饼图):
import { PieChart } from 'react-native-svg-charts';
const data = [
{ key: 1, value: 50, svg: { fill: '#600080' } },
{ key: 2, value: 10, svg: { fill: '#9900cc' } },
{ key: 3, value: 40, svg: { fill: '#c61aff' } },
];
<PieChart
style={{ height: 200 }}
data={data}
innerRadius={'60%'}
padAngle={0.03}
/>
自定义 SVG 图表
对于需要完全自定义的场景,可以结合 react-native-svg 手动绘制图表。
安装:
npm install react-native-svg
示例代码(简单折线图):
import Svg, { Polyline, G, Line, Text } from 'react-native-svg';
<Svg height="200" width="300">
<G y={150}>
<Line x1="0" y1="0" x2="300" y2="0" stroke="grey" />
{[0, 50, 100, 150, 200, 250].map((x, i) => (
<G key={i}>
<Line x1={x} y1="0" x2={x} y2="5" stroke="grey" />
<Text x={x} y="20" fill="black" textAnchor="middle">{i}</Text>
</G>
))}
<Polyline
points="0,40 50,80 100,120 150,30 200,60 250,100"
fill="none"
stroke="blue"
strokeWidth="2"
/>
</G>
</Svg>
选择建议
- 对于快速实现标准图表,推荐 react-native-chart-kit
- 需要高度定制化时,选择 victory-native
- 对性能有严格要求时,考虑 react-native-svg-charts
- 特殊需求可基于 react-native-svg 自行实现
所有方案均需要确保已正确链接原生依赖(React Native 0.60+ 自动链接)。







