Echarts 抽离相同配置

660 阅读1分钟

在一个项目中如果要用到多个echarts图表,每个图表的option都多少会有相同的配置。

这种情况可以将这些公共部分抽离出来,然后用 echarts.registerTheme(主题名称,commonOptions)

echartsTheme.ts

export const customTheme = {
  themeName: 'my_theme',
  theme: {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.40)',
      borderColor: 'rgba(255,255,255,0.50)',
      textStyle: {
        color: '#fff',
      },
    },
    grid: {
      borderWidth: 1,
      containLabel: true,
    },
    categoryAxis: { //axis的类型为'category'的公共配置
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255,255,255,0.1)',
        },
      },

      axisTick: {
        show: false,
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: 'rgba(255,255,255,0.8)',
        },
      },
      splitLine: {
        show: false,
      },
    },
    valueAxis: { //axis的类型为'value'的公共配置
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255,255,255,0.1)',
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: 'rgba(255,255,255,0.8)',
        },
      },
      splitLine: {
        show: false,
      },
    },
    bar: {
      barCategoryGap: '55%',
    },
  },
}

barChart.tsx

import React from 'react'
import * as echarts from 'echarts'
import ReactECharts from 'echarts-for-react'
import { customTheme } from '@/style/echartsTheme'
// 导入公共配置
echarts.registerTheme(customTheme.themeName, customTheme.theme)

interface BarChartProps {}

const BarChart: React.FC<BarChartProps> = () => {
  const options = {
   // ...在这里只需设置只有barChart能用到的配置即可
  }
  return <ReactECharts theme={customTheme.themeName} style={{ width: '100%' }} option={options} />
}

export default React.memo(BarChart)