• 使用react-grid-layout和echarts-for-react实现一个支持拖拽的自定义响应式dashboard页面


    使用react-grid-layout和echarts-for-react实现一个支持拖拽的自定义响应式dashboard页面

    需求概要

    在前端工作中,我们会经常遇到自定义dashboard页这样的需求。然后我想做一个能够让用户可以在面板上自由的拖拽,固定(不允许拖拽),拖拉改变大小、新增,删除组件。组件可以是各种echarts图形,也可是各种数据表格。通过各个组件的拖拽组合,从而让用户自定义需要的dashboard页。

    我们直接先来看最终的效果

    请添加图片描述

    技术栈

    那我们这里就会是用到react-grid-layoutecharts-for-react

    首先echarts-for-react,顾名思义就是用来绘制echarts图表的,这里不过多解释。然后react-grid-layout 是一个网格布局系统,可以实现响应式的网格布局,并且支持分割点(breakpoints)的设置,灵活运用可以方便的实现拖拽式组件的实现。

    具体使用就不多介绍了,可以直接去官网看看,例子很多也很详细:https://github.com/react-grid-layout/react-grid-layout

    简单实现

    下面是dashboard的主渲染入口

    import React, {useState} from "react";
    import 'react-grid-layout/css/styles.css'
    import 'react-resizable/css/styles.css'
    import {Layout, Responsive, WidthProvider} from "react-grid-layout";
    import {Button} from "antd";
    import {findIndex} from "lodash";
    import './dashboard.css'
    import WidgetLoadingSpin from "@/pages/Dashboard/Detail/WidgetLoadingSpin";
    import {CloseOutlined, LockOutlined, QuestionCircleOutlined, UnlockOutlined} from "@ant-design/icons";
    const BarChartWidgetLazy = React.lazy(() => import('@/pages/Dashboard/Detail/Widget/BarChartWidget'));
    const PieChartWidgetLazy = React.lazy(() => import('@/pages/Dashboard/Detail/Widget/PieChartWidget'));
    const ResponsiveReactGridLayout = WidthProvider(Responsive);
    
    interface DashboardWidgetInfo {
      widgetName: string,
      layout: Layout
    }
    
    function DashboardGird() {
    
      const [widgets, setWidgets] = useState<DashboardWidgetInfo[]>([]);
      const [currentCols, setCurrentCols] = useState<number>(12);
    
      const getLayouts: any = () => {
        return widgets.map(item => item.layout);
      }
    
    
      const setLayoutStatic = (widget: DashboardWidgetInfo, staticFlag: boolean) => {
        const index = findIndex(widgets, (w: any) => w.widgetName === widget.widgetName);
        if (index !== -1) {
          const updateWidget = widgets[index];
          updateWidget.layout.static = staticFlag;
          widgets.splice(index, 1, {...updateWidget});
          const newWidgets = [...widgets];
          setWidgets(newWidgets);
        }
      }
    
      const lockWidget = (widget: DashboardWidgetInfo) => {
        setLayoutStatic(widget, true);
      }
    
      const unlockWidget = (widget: DashboardWidgetInfo) => {
        setLayoutStatic(widget, false);
      }
    
      const onRemoveWidget = (widget: DashboardWidgetInfo) => {
        const widgetIndex = findIndex(widgets, (w: any) => w.layout.i === widget.layout.i);
        if (widgetIndex !== -1) {
          widgets.splice(widgetIndex, 1);
          const newWidgets = [...widgets];
          setWidgets(newWidgets);
        }
      }
    
      const getWidgetComponent = (widgetName: string) => {
        if (widgetName === 'PieChartWidget') { //可以改成策略
          return (<React.Suspense fallback={<WidgetLoadingSpin/>}>
            <PieChartWidgetLazy/>
          </React.Suspense>);
        } else {
          return (<React.Suspense fallback={<WidgetLoadingSpin/>}>
            <BarChartWidgetLazy/>
          </React.Suspense>);
        }
      }
    
    
      const createWidget = (widget: DashboardWidgetInfo) => {
        return (
            <div className={'dashboard-widget-wrapper'} key={widget.layout.i} data-grid={widget.layout}>
              <span className='dashboard-widget-header'>
                <QuestionCircleOutlined className={'dashboard-widget-header-icon'}/>
                {widget.layout.static ? <LockOutlined className={'dashboard-widget-header-icon'} onClick={() => unlockWidget(widget)}/> : (
                    <UnlockOutlined className={'dashboard-widget-header-icon'} onClick={() => lockWidget(widget)}/>)}
                <CloseOutlined className={'dashboard-widget-header-icon'} onClick={() => onRemoveWidget(widget)}/>
              </span>
              {getWidgetComponent(widget.widgetName)}
            </div>
        );
      }
    
    
      const onAddWidget = () => {
        const x = (widgets.length * 3) % (currentCols);
        const widgetName = x % 2 == 0 ? 'BarChartWidget' : 'PieChartWidget'
        const newWidgets = [...widgets, {
          widgetName: widgetName,
          layout: {i: widgetName, x: x, y: Infinity, w: 3, h: 2, static: false}
        }] as DashboardWidgetInfo[];
        setWidgets(newWidgets);
      }
    
      const onBreakpointChange = (newBreakpoint: string, newCols: number) => {
        setCurrentCols(newCols);
      }
    
      const onLayoutChange = (layouts: any[]) => {
        for (const layout of layouts) {
          const updateIndex = findIndex(widgets, (w) => w.layout.i === layout.i);
          if (updateIndex !== -1) {
            const updateWidget = widgets[updateIndex];
            updateWidget.layout = layout;
            widgets.splice(updateIndex, 1, {...updateWidget});
          }
        }
        const newWidgets = [...widgets];
        setWidgets(newWidgets);
      }
    
      return (
          <>
            <Button onClick={onAddWidget}>add widget</Button>
            <ResponsiveReactGridLayout
                layouts={getLayouts()}
                className={'layouts'}
                onLayoutChange={onLayoutChange}
                onBreakpointChange={onBreakpointChange}>
              {widgets?.map(item => createWidget(item))}
            </ResponsiveReactGridLayout>
          </>
      );
    }
    
    export default DashboardGird
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127

    然后接下来是自己的一些自定制化的一些图表或者表格的组件

    import React from "react";
    import WidgetLoadingSpin from "@/pages/Dashboard/Detail/WidgetLoadingSpin";
    
    const ReactEchartsLazy = React.lazy(() => import('echarts-for-react'));
    
    function PieChartWidget() {
      const getPieChart = () => {
        return {
          color: ['#3AA1FF', '#36CBCB', '#4ECB73', '#FBD338'],
          tooltip: {
            trigger: 'item',
            formatter: '{a} 
    {b}: {c} ({d}%)'
    }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, series: [{ name: '消费能力', type: 'pie', radius: ['40%', '55%'], center: ['50%', '55%'], avoidLabelOverlap: true, itemStyle: { normal: { borderColor: '#FFFFFF', borderWidth: 2 } }, label: { normal: { show: false, }, }, labelLine: { normal: { show: false } }, data: [{ name: 'a', value: '20' }, { name: 'b', value: '40' }, { name: 'c', value: '10' }, { name: 'd', value: '10' }] }] }; } return (<React.Suspense fallback={<WidgetLoadingSpin/>}> <ReactEchartsLazy option={getPieChart()} notMerge={true} lazyUpdate={true} style={{width: '100%', height: '100%'}}/> </React.Suspense>) } export default PieChartWidget
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    import React from "react";
    import WidgetLoadingSpin from "@/pages/Dashboard/Detail/WidgetLoadingSpin";
    
    const ReactEchartsLazy = React.lazy(() => import('echarts-for-react'));
    
    function BarChartWidget() {
    
      const getBarChart = () => {
        return {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'category',
            data: ['2014', '2015', '2016', '2017', '2018', '2019'],
            axisLine: {
              lineStyle: {
                color: '#8FA3B7',//y轴颜色
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#6D6D6D',
              }
            },
            axisTick: {show: false}
          }],
          yAxis: [{
            type: 'value',
            splitLine: {show: false},
            //max: 700,
            splitNumber: 3,
            axisTick: {show: false},
            axisLine: {
              lineStyle: {
                color: '#8FA3B7',//y轴颜色
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#6D6D6D',
              }
            },
          }],
          series: [
    
            {
              name: 'a',
              type: 'bar',
              barWidth: '40%',
              itemStyle: {
                normal: {
                  color: '#FAD610'
                }
              },
              stack: '信息',
              data: [320, 132, 101, 134, 90, 30]
            },
            {
              name: 'b',
              type: 'bar',
              itemStyle: {
                normal: {
                  color: '#27ECCE'
                }
              },
              stack: '信息',
              data: [220, 182, 191, 234, 290, 230]
            },
            {
              name: 'c',
              type: 'bar',
              itemStyle: {
                normal: {
                  color: '#4DB3F5'
                }
              },
              stack: '信息',
              data: [150, 132, 201, 154, 90, 130]
            }
          ]
        };
      }
    
      return (
          <React.Suspense fallback={<WidgetLoadingSpin/>}>
            <ReactEchartsLazy
                option={getBarChart()}
                notMerge={true}
                lazyUpdate={true}
                style={{width: '100%', height: '100%'}}/>
          </React.Suspense>)
    }
    
    
    export default BarChartWidget
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108

    这里用到了React.lazy,所以还需要定制一下未加载时候渲染出来的组件

    import {Spin} from "antd";
    import React from "react";
    import './dashboard.css'
    function WidgetLoadingSpin(){
    
      return (
          <div className={'dashboard-widget-loading'}><Spin tip={'Loading...'}/></div>
      )
    }
    
    
    export default WidgetLoadingSpin;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    最后是一些简单的CSS样式

    .dashboard-widget-loading {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%
    }
    
    .dashboard-widget-wrapper {
      background: white;
    }
    
    .dashboard-widget-wrapper:hover {
      box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.9)
    }
    
    .dashboard-widget-header {
      display: none;
    }
    
    .dashboard-widget-header-icon {
      margin: 4px;
      opacity: 0.7;
    }
    
    .dashboard-widget-header-icon:hover {
      color: #00508E;
    }
    
    
    .dashboard-widget-wrapper:hover .dashboard-widget-header {
      position: absolute;
      right: 7px;
      top: 2px;
      cursor: pointer;
      z-index: 999;
      display: block;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    参考

    https://github.com/react-grid-layout/react-grid-layout

    https://github.com/Bilif/react-drag-grid

    react-grid-layout实现拖拽,网格布局

    React-grid-layout 一个支持拖拽的栅格布局库

    echarts-for-react

    在 React 中使用 echarts-for-react / react ,如,柱状图,折线图,饼图

    react-grid-layout核心功能实现

    React的动态加载(lazy import)

    深入理解React:懒加载(lazy)实现原理

    react-grid-layout 使用说明

    React-Grid-Layout

    基于react-grid-layout实现可视化拖拽

    React 实现炫酷的可拖拽网格布局

  • 相关阅读:
    腾讯云5年服务器2核4G和4核8G配置租用价格表
    PyQt5中的layout布局
    网站自动翻译-网站批量自动翻译-网站免费翻译导出
    jpa整合sharding-jdbc不分库分表(包括id主键生成策略的使用)
    重塑语言智能未来:掌握Transformer,驱动AI与NLP创新实战
    凌恩客户文章|Nature子刊-水体RNA宏病毒组
    如何正确使用 WEB 接口的 HTTP 状态码和业务状态码?
    基于Dijkstra和A*算法的机器人路径规划(Matlab代码实现)
    Java输入开始时间和结束输出全部对应的年月、年份、日期
    算法的时间复杂度
  • 原文地址:https://blog.csdn.net/cckevincyh/article/details/128086177