美文网首页
模态框引起的思考

模态框引起的思考

作者: 张义飞 | 来源:发表于2018-11-23 10:43 被阅读0次

    如何优雅的使用模态框

    大家在使用antd中的模态框时是不是有一些痛点,比如要处理visible显示隐藏的逻辑,
    如果一个页面中Modal太多,我们就要去处理多个visible状态,但是这样一来页面的逻辑就变的,
    越来的越乱,所以下面我就给大家介绍一下我是怎么一步一步去简化这个控件的使用过程的。

    Modal框的初体验

    按照官网上的例子我写出了我的第一个模态框。

    import { Modal, Button } from 'antd';
    
    class App extends React.Component {
      state = { visible: false }
    
      showModal = () => {
        this.setState({
          visible: true,
        });
      }
    
      handleOk = (e) => {
        console.log(e);
        this.setState({
          visible: false,
        });
      }
    
      handleCancel = (e) => {
        console.log(e);
        this.setState({
          visible: false,
        });
      }
    
      render() {
        return (
          <div>
            <Button type="primary" onClick={this.showModal}>
              Open Modal
            </Button>
            <Modal
              title="Basic Modal"
              visible={this.state.visible}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
            >
              <p>Some contents...</p>
              <p>Some contents...</p>
              <p>Some contents...</p>
            </Modal>
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, mountNode);
    

    后来我的页面里又多了几个Modal,于是我又写了几个Modal和几个visible去控制显示逻辑,在后来
    我就崩溃了....。

    状态组件

    后来我知道了什么是受控组件,什么是非受控组件。那么Modal框是要通过visible这个状态去控制显示隐藏,那么能不能通过封装,将这个状态让它内部消化类。后来我写了一个CommonModal,就是下面的例子。

        
    import React from "react";
    import { Modal } from "antd";
    
    export default class CommonModal extends React.Component {
      state = { visible: false };
    
      showModal = () => {
        this.setState({
          visible: true
        });
      };
    
      handleOk = e => {
        this.setState({
          visible: false
        });
        this.props.onOk && this.props.onOk();
      };
    
      handleCancel = e => {
        console.log(e);
        this.setState({
          visible: false
        });
        this.props.onCancel && this.props.onCancel();
      };
    
      render() {
        return (
          <div>
            <button onClick={_ => this.showModal()}>打开模态框</button> // 这个地方可以灵活配置
            <Modal
              {...this.props}
              visible={this.state.visible}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
            >
              {this.props.children}
            </Modal>
          </div>
        );
      }
    }
    
    
    

    上面的代码我们只是简单的将antd的例子进行了一个封装,可以将灵活配置的地方通过属性传递过来这样
    外部就不需要进行控制visible这个状态了。好了,感觉用起来是不是舒服了一点,但是感觉还是有点不太舒服,比如我现在要在网络出错是弹出一个Modal框,render里面写了好多renderXXModal啊,如果我在点击某个按钮,或者做某件事情的时候,像调用一个方法一样调出Modal框,那该多好啊?其实antd给我们提供了这样的组件,比如Modal.confirm, Modal.success 等等。于是找到我模仿antd写出了下面的代码。

    进一步封装

    
    
    import { Modal } from 'antd';
    import { ModalFuncProps } from 'antd/lib/modal';
    import ReactDOM from 'react-dom';
    import React from 'react';
    
    /**
     *  example
     *
     * 1. 简单调用
     *  ShowModal();
     * 2. onOk可以提供一个Promise
     * ShowModal({
     *         content: <div>'Hello Modal'</div>,
     *         title: '我是测试的',
     *         onOk: () => Promise.resolve(123),
     *         onCancel: () => console.log('onCancel')
     *      })
     * 3. onOk可以提供一个方法
     *  ShowModal({
     *         content: <div>'Hello Modal'</div>,
     *         title: '我是测试的',
     *        onOk: () => console.log('onOk'),
     *        onCancel: () => console.log('onCancel')
     *       })
     * 4. onOk可以返回一个bool值来进行判断是否满足条件,然后在进行关闭
     *    比如你有一个表格,想要进行表格验证,如果不满足验证就提示错误,而不是关闭
     *    模态框
     *
     *  比如下面的列子
     *
     *  state: any = {
     *    name: '',
     *  }
     *  renderForm = () => {
     *   const { name } = this.state;
     *   return (
     *     <Form.Item
     *       help={name.length === 0 ? '不能为空' : ''}
     *      validateStatus={name.length > 0 ? 'success' : 'error'}
     *     >
     *       <Input
     *         value={name}
     *        onChange={e => this.setState({name: e.target.value})}
     *       />
     *    </Form.Item>
     *   );
     * }
     *
     *    ShowModal({
     *             content: this.renderForm(),
     *             title: '我是测试的',
     *             onOk: () => {
     *               console.log('在这里做其他事情', this.state.name);
     *               return this.state.name.length > 0;
     *             },
     *            onCancel: () => console.log('onCancel')
     *           });
     *
     */
    
    function ShowModal(config?: ModalFuncProps) {
      let currentConfig = { ...config, close, visible: true } as any;
      const div = document.createElement('div');
      document.body.appendChild(div);
    
      function update(newConfig: ModalFuncProps) {
        currentConfig = {
          ...currentConfig,
          ...newConfig,
        };
        render(currentConfig);
      }
    
      function destroy() {
        const unmountResult = ReactDOM.unmountComponentAtNode(div);
        if (unmountResult && div.parentNode) {
          div.parentNode.removeChild(div);
        }
      }
    
      function handleOnOk(props: ModalFuncProps) {
        const { onOk } = props;
        if (typeof onOk === 'function') {
          const isVaild = props.onOk() || true;
          if (isVaild) {
            update({visible: false});
            destroy();
          }
        } else if (typeof onOk === 'object') {
          // tslint:disable-next-line:no-unused-expression
          (onOk as any).finally = () => {
            update({visible: false});
            props.onOk();
            destroy();
          };
        } else {
          throw new Error('onOk只支持func或promise');
        }
      }
    
      function handleOnCancel(props: ModalFuncProps) {
        const { onCancel } = props;
        update({visible: false});
        if (typeof onCancel === 'function') {
          props.onCancel();
          destroy();
        }
      }
    
      function render(props: ModalFuncProps) {
        ReactDOM.render(
          <Modal
            {...props}
            onOk={_ => handleOnOk(props)}
            onCancel={_ => handleOnCancel(props)}
          >
            { props.content ? props.content : <div>{'example'}</div>}
          </Modal>,
          div
        );
      }
    
      render(currentConfig);
      return {
        update,
        destroy,
      };
    }
    
    export default ShowModal;
    
    

    其实到这里我还是有些顾虑:

    1. 如果这样去操作Dom是否会影响性能
    2. 如果服务器端渲染这样document对象没法使用了,我说的意思是比如您在服务器端发了一个网络请求然后在失败的时候调用了这个方法,这种情况。我也是猜测,没做实验。
    3. 如果被高阶函数包裹后,出现内存泄漏了怎么办。。。

    相关文章

      网友评论

          本文标题:模态框引起的思考

          本文链接:https://www.haomeiwen.com/subject/ilodqqtx.html