一个 chart-x 标签搞定数据可视化, https://github.com/Tencent/omi 和 chart.JS https://www.chartjs.org/ 强力加持
支持的图表
- <chart-bar />
- 柱状图
- <chart-line />
- 线图
- <chart-scatter />
- 散点图
- <chart-pie />
- 饼图
- <chart-doughnut />
- 环状图
- <chart-radar />
- 雷达图
- <chart-polar-area />
极区图
<chart-bubble /> 气泡图
在线互动例子
- Bar charts
- Simple
- Vertical
- Horizontal
- Multi Axis
- Stacked Group
- Line charts
- Base
- Multi Axis
- Stepped
- Fill
- Interpolation Modes
- Point Sizes
- Styles
- Point Styles
- Scatter charts
- Base
- Multi Axis
- Other charts
- Pie
- Doughnut
- Radar
- PolarArea
- Bubble
- Bar Line
安装
NPM i omi-chart
快速上手
- import 'omi-chart'
- define('my-app', class extends WeElement {
- install(){
- this.chartData = {
- labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
- datasets: [{
- label: '# of Votes',
- data: [12, 19, 3, 5, 2, 3],
- backgroundColor: '#f391a9',
- borderColor: '#ef5b9c',
- borderWidth: 1
- }]
- }
- this.chartOptions = {
- scales: {
- yAxes: [{
- ticks: {
- beginAtZero: true
- }
- }]
- }
- }
- }
- render(props, data) {
- return (
- <div>
- <chart-bar width={600} data={this.chartData} options={this.chartOptions} />
- </div>
- )
- }
- })
- render(<my-App />, 'body')
具体的传入 options 和 data 格式可以查看 chart.JS 文档 https://www.chartjs.org/docs/latest/ .
原理
代码量不多, 直接看源码:
- import { WeElement, define } from 'omi'
- import Chart from 'chart.js'
- class ChartBase extends WeElement {
- receiveProps(props) {
- this.chart.data = props.data
- this.chart.options = props.options
- this.chart.update()
- }
- render(props) {
- return (
- <div style={{ width: props.width + 'px', height: props.height + 'px' }}>
- <canvas ref={(e) => { this.canvas = e }}>
- </canvas>
- </div>
- )
- }
- }
- define('chart-bar', class extends ChartBase {
- installed() {
- this.chart = new Chart(this.canvas.getContext('2d'), {
- type: this.props.horizontal ? 'horizontalBar' : 'bar',
- data: this.props.data,
- options: this.props.options
- })
- }
- })
- define('chart-line', class extends ChartBase {
- installed() {
- this.chart = new Chart(this.canvas.getContext('2d'), {
- type: 'line',
- data: this.props.data,
- options: this.props.options
- })
- }
- })
- define('chart-scatter', class extends ChartBase {
- installed() {
- this.chart = new Chart.Scatter(this.canvas.getContext('2d'), {
- data: this.props.data,
- options: this.props.options
- })
- }
- })
所有的图表继承自 ChartBase,ChartBase 继承自 WeElement.omi-chart 会根据传入的 props 创建不同类型的 Chart.
其中利用了勾子函数 receiveProps.
receiveProps - 当父组件重新刷新的时候会触发改勾子函数.
预告一下: Omi 马上要支持 IE9 和所有的移动端浏览器, 敬请期待.
Star & Fork
→ Omi Chart ←
来源: https://juejin.im/post/5c11c316e51d457b00690b97