@duxapp/react-native-chartjs
v0.1.0
Published
Chart.js wrapper for React Native built on top of @duxapp/react-native-canvas
Downloads
42
Maintainers
Readme
@duxapp/react-native-chartjs
@duxapp/react-native-chartjs 是一个基于 @duxapp/react-native-canvas 的 React Native chart.js 封装。
安装
如果你的项目还没有安装 @shopify/react-native-skia,请先安装它:
yarn add @shopify/react-native-skia或
npm install @shopify/react-native-skia然后再安装 @duxapp/react-native-chartjs:
yarn add @duxapp/react-native-chartjs或
npm install @duxapp/react-native-chartjs需要安装的 peer dependencies:
reactreact-native@shopify/react-native-skia
使用
import { useEffect, useState } from 'react';
import { ScrollView, StyleSheet } from 'react-native';
import { Chart } from '@duxapp/react-native-chartjs';
import {
ArcElement,
BarController,
BarElement,
BubbleController,
CategoryScale,
Chart as ChartJS,
DoughnutController,
Filler,
Legend,
LineController,
LineElement,
LinearScale,
PieController,
PointElement,
PolarAreaController,
RadarController,
RadialLinearScale,
ScatterController,
Tooltip,
} from 'chart.js';
let registered = false;
const ensureRegister = () => {
if (registered) {
return;
}
ChartJS.register(
ArcElement,
BarController,
BarElement,
BubbleController,
CategoryScale,
DoughnutController,
Filler,
Legend,
LineController,
LineElement,
LinearScale,
PieController,
PointElement,
PolarAreaController,
RadarController,
RadialLinearScale,
ScatterController,
Tooltip
);
registered = true;
};
const labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const createConfig = () => ({
type: 'bar',
data: {
labels,
datasets: [
{
label: '销量',
data: labels.map(() => Math.round(Math.random() * 300)),
backgroundColor: '#3b82f6',
},
],
},
options: {
animation: {
duration: 800,
easing: 'easeOutCubic' as const,
},
maintainAspectRatio: false,
plugins: {
legend: { display: false },
},
scales: {
y: { beginAtZero: true },
},
},
});
export default function Demo() {
ensureRegister();
const [config, setConfig] = useState(() => createConfig());
useEffect(() => {
const timer = setInterval(() => {
setConfig(createConfig());
}, 1200);
return () => clearInterval(timer);
}, []);
return (
<ScrollView contentContainerStyle={styles.content}>
<Chart config={config} style={styles.chart} />
</ScrollView>
);
}
const styles = StyleSheet.create({
content: {
padding: 20,
},
chart: {
width: '100%',
height: 320,
borderRadius: 18,
overflow: 'hidden',
},
});说明
- 渲染图表前,需要先注册你实际使用到的 Chart.js controller、element、scale 和 plugin。
config会驱动图表更新,建议放在 state 中管理,数据变化时再主动替换。- 触摸事件会通过底层 canvas hook 转发给 Chart.js,所以点击、悬停类交互仍然可以工作。
