react-grid-layout的简单应用

react-grid-layout有什么用呢?

实现拖拽,网格布局

安装 react-grid-layout

npm install react-grid-layout

创建一个GridLayout组件


import React, { Component } from 'react';
import { Responsive, WidthProvider } from 'react-grid-layout';
import './index.scss';

const ResponsiveGridLayout = WidthProvider(Responsive);


class GridLayout extends Component {
    constructor(props) {
        super(props);
        this.state = {
          compactType: 'vertical',
          layouts:props.layout,
        };
    }
    componentWillMount() {
        this.getUserInfo()

    };
    componentWillUnmount() {
        // componentWillMount进行异步操作时且在callback中进行了setState操作时,需要在组件卸载时清除state
        this.setState = () => {
            return;
        };
    }

    //props发生变化时触发
  componentWillReceiveProps(props) {
    console.log({props})
    this.setState({
      layouts: [...props.layout]
    });
  }

    getUserInfo=()=>{
        var _EUlayoutArr = JSON.parse(localStorage.getItem("layoutArr"))
        if (_EUlayoutArr === null || _EUlayoutArr === undefined) {
            // console.log("--null----")
            this.setState({
              layouts:[
              { i: 'a', x: 0, y: 0, w: 15, h: 5 }, // w:8 是中, w:15 是大
              { i: 'b', x: 0, y: 0, w: 4, h: 5 }, // h:10, 是中, h:4,是小
              { i: 'c', x: 0, y: 0, w: 8, h: 10 },// w:8,是大,w:4,是中
              { i: 'd', x: 0, y: 0, w: 8, h: 10 }, // w:8,是大,w:4,是中
          ]})
            // this.setState({
            //     layout: [
            //         { i: 'a', x: 0, y: 0, w: 15, h: 5 }, // w:8 是中, w:15 是大
            //         { i: 'b', x: 0, y: 0, w: 4, h: 5 }, // h:10, 是中, h:4,是小
            //         { i: 'c', x: 0, y: 0, w: 8, h: 10 },// w:8,是大,w:4,是中
            //         { i: 'd', x: 0, y: 0, w: 8, h: 10 }, // w:8,是大,w:4,是中
            //     ]
            // })

        }
        else {
            // console.log("youzhi----")
            this.props.setLayout([..._EUlayoutArr])
            this.setState({
                layout: _EUlayoutArr
            })
            // this.state.layout = _EUlayoutArr
        }
    }
    
    //存储拖拽移动的位置到缓存
    onLayoutChange = (layout, layouts) => {
        console.log(layout, "=----layout----",layouts)
        let layoutArr = [];
        
        var index = -1;
        // localStorage.removeItem('CPlayoutArr')
        layout.forEach(({ i, x, y, w, h }) => {
            index++;
            layoutArr[index] = { i, x, y, w, h }
        })

        localStorage.setItem('layoutArr', JSON.stringify(layoutArr))
        this.props.setLayout([...layoutArr])
    }
    
    render() {
      // console.log('this.state.layouts', this.state.layouts )
      const {list} = this.props;
        return (
            <>
                <div className="dashboardContent">
                <ResponsiveGridLayout
                  className="layout" 
                  draggableCancel=".react-drag" // 加了这个类名是不能被移动的
                  layouts={{ lg: this.state.layouts }} 
                  measureBeforeMount={false}
                  rowHeight={30}
                  breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
                  cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
                  isResizable={false}
                  onLayoutChange={this.onLayoutChange}
                  margin={[24, 24]}
                  compactType={this.state.compactType}
                  preventCollision={!this.state.compactType}
                >
                  {list.map(i => {
                    return <div className='dragcontent' key={i.key}>
                    {i.component}
                </div>
                  })}
                   
                </ResponsiveGridLayout>
                </div>
            </>
        );
    }
}

export default GridLayout;

// index.scss
.dashboardContent { // 这个一定要设置,不然容易有偏移
	position: relative;
}

引用这个组件

import { useState } from 'react';
import GridLayout from './GridLayout/index';

const list = [
	{
		key: 'a', // 这个key一定要对应
		component: <TopBanner /> // 组件自己创建
	},
	{
		key: 'b',
		component: <PersonalInfo />
	},
	{
		key: 'c',
		component: <MyToDo />
	},
	{
		key: 'd',
		component: <Message />
	}
];

const Index = () => {
	const [ layout, setLayout ] = useState([
		{ i: 'a', x: 0, y: 0, w: 15, h: 5 }, // w:8 是中, w:15 是大
		{ i: 'b', x: 0, y: 5, w: 4, h: 5 }, // h:10, 是中, h:4,是小
		{ i: 'c', x: 0, y: 10, w: 8, h: 10 }, // w:8,是大,w:4,是中
		{ i: 'd', x: 0, y: 15, w: 8, h: 10 } // w:8,是大,w:4,是中
    ]);

	return (
		<div>
		<GridLayout list={list} layout={layout} setLayout={setLayout}>
                </GridLayout>
		</div>
	)
}

export default Index;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值