让 antd Model 变成可拖动弹窗

本想自己模仿 antd 写一套可以拖拽的弹窗,后来对如何让 antd 的 Model 拖拽起来 更感兴趣,

我把实现方式的关键点贴出来,供大家讨论。

1. 封装成一个公用组件

// 目录

├── src/
│   ├── components/
│   │   └── DragAntdModal/
│   │       ├── index.jsx
│   │       └── Drag.js

1.1 Drag.js 文件

如何拖拽就不详细介绍了,以前都写过,拖拽函数不是本文的关键点。

点击查看 Drag.js 文件代码

1.2 封装 Antd - Modal 成组件

这一步是关键,定时器的使用,将主线程的任务放到了宏任务,以成功获取元素。

import React, { Component } from "react";
// import styles from './index.less';
import { Modal } from 'antd';
// import PropTypes from "prop-types";
import Drag from "./Drag";
let timer = null;

class DragAntdModal extends Component {
  constructor(props) {
    super(props);
    // this.state = {

    // }
  };

  componentDidMount() {

  }

  componentWillReceiveProps(nextProps) {
    const { visible } = nextProps;
    if (visible !== this.props.visible) {
      this.showModalFn();
    };
  }

  componentWillUnmount() {
    if (timer) {
      clearTimeout(timer)
    }
  }

  showModalFn = () => {
    timer = setTimeout(function () {
      new Drag("ant-modal").init();
    }, 0)
  }

  render() {
    return (
      <Modal {...this.props}></Modal>
    )
  }
};

// DragAntdModal.propTypes = {
  // ...
// };

// DragAntdModal.defaultProps = {
  // ...
// };

export default DragAntdModal;

 

2. 在页面中使用

引入 DragAntdModal 组件之后和 antd 的 Modal 一样


import DragAntdModal from "components/DragAntdModal"; // 注意路径正确

 

3. 还有哪些地方可以改进

对细节要求高的,可以注意一下, onmousedown 的位置,和鼠标的样式。

 

4. 完整代码

点击查看

如果没明白,可以留言联系我

 

posted @ 2020-09-01 18:50  真的想不出来  阅读(1795)  评论(1编辑  收藏  举报