本想自己模仿 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. 完整代碼
如果沒明白,可以留言聯系我