[Silently] efforts to react-drag-grid

First put the project Address: https://github.com/Bilif/react-drag-grid
project operating results

thanks to the selfless open-source programmers to
look at the project entry file

//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

The main contents can be seen mainly in the App.js
then we look App.js

//App.js
import React from 'react';
import './App.css';
import DragLayout from './DragLayout';

function App() {
  return (
    <DragLayout></DragLayout>
  );
}

export default App;

We can see the main reference App is DragLayout component
is the core function point DragLayout assembly
in DragLayout we will see references to some of the components
such as antd, layout and style to
react-grid-layout is easy to use drag, adaptive layout react plug
its use is

import { WidthProvider, Responsive } from "react-grid-layout";
const ResponsiveReactGridLayout = WidthProvider(Responsive);

Rendering the render layout method may be dragged in React. ResponsiveReactGridLayout component has a plurality of attributes.
cols: defines the response layout into columns.
rowHeight: responsive layout assembly line high.
onLayoutChange: This function is triggered when a layout in response to a drag occurs or zoom components.

     <ResponsiveReactGridLayout
            className="layout"
            {...this.props}
            layouts={this.state.layouts}
            onLayoutChange={(layout, layouts) =>
              this.onLayoutChange(layout, layouts)
            }
          >
            {this.generateDOM()}
          </ResponsiveReactGridLayout>

Use echarts-for-react plug-ins can call echarts interface React directly render Echarts chart, simply pass the relevant parameters and data can be.
installation

npm install --save echarts-for-react]
npm install --save echarts

use

  let component = (
        <ReactEcharts
          option={option}
          notMerge={true}
          lazyUpdate={true}
          style={{width: '100%',height:'100%'}}
        />
      )

Side of the three kinds of the chart in FIG encapsulated

//chart.js
export function getBarChart() {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器,坐标轴触发有效
        type: 'shadow' // 默认为直线,可选为:'line' | '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 option;
}

export function getLineChart() {
  //option
  const option = {
    color: ['#D53A35'],
    tooltip: {
      trigger: 'axis',
      //formatter: "{b} <br> 合格率: {c}%"
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      name: '',
      boundaryGap: false,
      axisLine:{
        show:false,
        lineStyle:{
          color:'#525252'
        }
      },
      axisTick:{
        show:false
      },
      axisLabel:{
        color:'#525252'
      },
      data: ['01', '02', '03', '04', '05', '06', '07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24']
    },
    yAxis: {
      type: 'value',
      name: '',
      axisLine:{
        show:false,
      },
      axisTick:{
        show:false
      },
      axisLabel:{
        color:'#525252'
      },
      splitLine:{
        lineStyle:{
          type:'dotted',
          color:'#AAA'//F3F3F3
        }
      }
    },
    series: [{
      name: 'a',
      type: 'line',
      symbol: 'circle',
      data: [100,120, 132, 101, 134, 90, 230, 210,80,20,90,210,200,100,120, 132, 101, 134, 90, 230, 210,80,20,90]
    }
    ]
  };
  return option;
}

export function getPieChart() {
  //option
  const option = {
    color: ['#3AA1FF', '#36CBCB', '#4ECB73', '#FBD338'],
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{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 option;
}

GenerateDOM function by generation component layout, component first traverse the first array, a histogram is determined production assembly, by type of each component
polyline component, assembly, or pie chart. Each component must define a globally unique key value. data-grid its binding properties for each component.

  generateDOM = () => {
    return _.map(this.state.widgets, (l, i) => {
      let option;
      if (l.type === 'bar') {
        option = getBarChart();
      }else if (l.type === 'line') {
        option = getLineChart();
      }else if (l.type === 'pie') {
        option = getPieChart();
      }
      let component = (
        <ReactEcharts
          option={option}
          notMerge={true}
          lazyUpdate={true}
          style={{width: '100%',height:'100%'}}
        />
      )
      return (
        <div key={l.i} data-grid={l}>
          <span className='remove' onClick={this.onRemoveItem.bind(this, i)}>x</span>
          {component}
        </div>
      );
    });
  };

AddItem to add components by function.
Each component properties are as follows:

x: x coordinate component
y: coordinate in the y-axis component
w: width of the component
h: height of the component
i: key value component

addItem(type,widgetId) {
    const addItem = {
      x: (this.state.widgets.length * 2) % (this.state.cols || 12),
      y: Infinity, // puts it at the bottom
      w: 2,
      h: 2,
      i: widgetId || new Date().getTime().toString(),
    };
    this.setState(
      {
        widgets: this.state.widgets.concat({
          ...addItem,
          type,
        }),
      },
    );
  };

To remove components increase by onRemoveItem function.

onRemoveItem(i) {
    console.log(this.state.widgets)
    this.setState({
      widgets: this.state.widgets.filter((item,index) => index !=i)
    });

  }

DragLayout.js all code

//DragLayout
import React, { PureComponent } from 'react';
import { Layout,Button } from 'antd';
import { WidthProvider, Responsive } from "react-grid-layout";
import _ from "lodash";
import ReactEcharts from 'echarts-for-react';
import { getBarChart,getLineChart,getPieChart } from "./chart";

const ResponsiveReactGridLayout = WidthProvider(Responsive);
const { Header, Content} = Layout;

export default class DragLayout extends PureComponent {
  static defaultProps = {
    cols: { lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 },
    rowHeight: 100,
  };

  constructor(props) {
    super(props);

    this.state = {
      layouts: this.getFromLS("layouts") || {},
      widgets:[]
    }
  }

  getFromLS(key) {
    let ls = {};
    if (global.localStorage) {
      try {
        ls = JSON.parse(global.localStorage.getItem("rgl-8")) || {};
      } catch (e) {
        /*Ignore*/
      }
    }
    return ls[key];
  }

  saveToLS(key, value) {
    if (global.localStorage) {
      global.localStorage.setItem(
        "rgl-8",
        JSON.stringify({
          [key]: value
        })
      );
    }
  }
  generateDOM = () => {
    return _.map(this.state.widgets, (l, i) => {
      let option;
      if (l.type === 'bar') {
        option = getBarChart();
      }else if (l.type === 'line') {
        option = getLineChart();
      }else if (l.type === 'pie') {
        option = getPieChart();
      }
      let component = (
        <ReactEcharts
          option={option}
          notMerge={true}
          lazyUpdate={true}
          style={{width: '100%',height:'100%'}}
        />
      )
      return (
        <div key={l.i} data-grid={l}>
          <span className='remove' onClick={this.onRemoveItem.bind(this, i)}>x</span>
          {component}
        </div>
      );
    });
  };

  addChart(type) {
    const addItem = {
      x: (this.state.widgets.length * 3) % (this.state.cols || 12),
      y: Infinity, // puts it at the bottom
      w: 3,
      h: 2,
      i: new Date().getTime().toString(),
    };
    this.setState(
      {
        widgets: this.state.widgets.concat({
          ...addItem,
          type,
        }),
      },
    );
  };

  onRemoveItem(i) {
    console.log(this.state.widgets)
    this.setState({
      widgets: this.state.widgets.filter((item,index) => index !=i)
    });

  }

  onLayoutChange(layout, layouts) {
    this.saveToLS("layouts", layouts);
    this.setState({ layouts });
  }

  render() {
   return(
     <Layout>
      <Header style={{ position: 'fixed', zIndex: 1, width: '100%','padding': '0 30px' }}>
        <Button type="primary" style={{'marginRight':'7px'}} onClick={this.addChart.bind(this,'bar')}>添加柱状图</Button>
        <Button type="primary" style={{'marginRight':'7px'}} onClick={this.addChart.bind(this,'line')}>添加折线图</Button>
        <Button type="primary" style={{'marginRight':'7px'}} onClick={this.addChart.bind(this,'pie')}>添加饼图</Button>
      </Header>
      <Content style={{ marginTop: 44 }}>
        <div style={{ background: '#fff', padding: 20, minHeight: 800 }}>
          <ResponsiveReactGridLayout
            className="layout"
            {...this.props}
            layouts={this.state.layouts}
            onLayoutChange={(layout, layouts) =>
              this.onLayoutChange(layout, layouts)
            }
          >
            {this.generateDOM()}
          </ResponsiveReactGridLayout>
        </div>
      </Content>
    </Layout>
   )}
}

Section discusses the learning content from blog: https://juejin.im/post/5cda5719e51d453a36384923

Guess you like

Origin www.cnblogs.com/smart-girl/p/11428207.html