React echarts 组件的封装使用案例
作者:栖北
这篇文章主要介绍了React echarts 组件的封装,本文通过示例代码给大家介绍的非常详细,需要的朋友可以参考下
React echarts 组件的封装
import React, { useEffect, useRef } from 'react'; import { useSize, useDebounceEffect } from 'ahooks'; import LoopShowTooltip from './echartsTooltipLoop'; import * as echarts from 'echarts'; const CommonChart = props => { const { chartId, options, autoTooltip } = props; const chartRef = useRef(); const size = useSize(chartRef); const loopRef = useRef(); useEffect(() => { let chartDom; let myChart; if (loopRef.current) { loopRef.current?.clearLoop(); loopRef.current = null; } setTimeout(() => { if (loopRef.current) { loopRef.current?.clearLoop(); loopRef.current = null; } if (chartRef) { chartDom = chartRef.current; myChart = echarts.init(chartDom); options && myChart.setOption(options); if (autoTooltip) { loopRef.current = new LoopShowTooltip(myChart, options, {}); } } }); window.onresize = () => { myChart.resize(); }; return () => { window.onresize = null; loopRef?.current?.clearLoop(); loopRef.current = null; }; }, [chartId, options]); useDebounceEffect(() => { let myChart; let chartDom; if (chartRef) { chartDom = chartRef.current; myChart = echarts.init(chartDom); options && myChart.setOption(options); myChart.resize(); } window.onresize = () => { myChart.resize(); }; }, [size], { wait: 100, }); return <div ref={chartRef} style={{ width: '100%', height: '100%' }}></div>; }; export default CommonChart;
使用案例
import React from "react"; import CommonChart from './pages/CommonChart/UI' const Demo = () => { let echarData = [122,112,233,123,122,788,900]; let yAxisData = ['星期一','星期二','星期三','星期四','星期五','星期六','星期日']; const chartOptions = { grid: { top: '8%', bottom: '15%', left: '30%', right: '16%', // containLabel: true, }, tooltip: { trigger: 'item', show: true, backgroundColor: '#3A3F4D', borderWidth: 0, textStyle: { // 提示框浮层的文本样式。 color: '#B1B6C2', fontStyle: 'normal', fontWeight: 'normal', fontFamily: 'sans-serif', fontSize: 14, }, formatter: record => { let result = `${record.name}:${record.value} 次`; return result; }, }, xAxis: { type: 'value', boundaryGap: [0, 0.01], splitLine: { show: false, }, }, yAxis: { type: 'category', data: yAxisData, scale: true, axisTick: { // x轴刻度线 show: false, alignWithLabel: true, }, axisLabel: { interval: 0, width: 80, overflow: 'truncate', ellipsis: '...', align: 'left', margin: 80, }, axisLine: { // 坐标轴 show: false, }, }, series: [ { name: '2011', type: 'bar', showBackground: true, backgroundStyle: { color: '#1A1E28', }, barWidth: 12, // 柱图宽度 itemStyle: { normal: { // 柱状图上显示数量 label: { show: true, // 是否显示 position: [220, 0], // 位置 formatter: '{@value}' + '次', // 内容 color: '#A5ADBA', // 文字颜色 }, color: '#2275F0', // 柱子颜色 }, }, data: echarData, }, ], }; return ( <div style={{height:300, width: 400}}> <CommonChart options={chartOptions} /> </div> ); }; export default Demo;
到此这篇关于React echarts 组件的封装的文章就介绍到这了,更多相关React echarts 组件封装内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!