react 的弹出层你们一般怎么写

流程

  1. 分析:交互意图以及需求
  2. 结构:HTML+CSS实现静态结构
  3. 接口:定义公共接口
  4. 实现:抽象=>细节,实现功能接口、暴露事件
  5. 完善:便利接口,插件封装、重构等

实例 :Modal组件

模态组件是最常用到等组件,Modal通过弹出一个高聚集性的窗口来立即捕获当前用户注意力

需求分解

  1. 模态窗口水平锤子居中
  2. 半透明遮罩。
  3. 可以自定义标题和内容
  4. 提供取消和确认操作

页面结构分解

  1. 遮罩层>窗体结构
  2. 窗体>头部+内容+按钮

页面结构代码:

使用添加一个辅助线的方法

使窗体垂直水平居中
css居中关键实现代码

.m-modal{
    text-align:center;
}
.modal_align,.modal_wrap{
    display:inline-block;
    vertical-align:middle;
}
.modal_align{
    height:100%;
    width:1px;
    line-height:100%;
}

定义公共接口和方法

  • 接口设置

    1. 内容配置
    2. 动画设置
    3. 取消操作回掉
    4. 确认操作回掉

    接口代码实现

var modal = new Modal({
    // 1. 内容配置
    cotent: "内容在此", //可传入节点和字符串
    // 2. 动画设置
    animation: {
        enter: 'bounceIn',
        leave: 'bounceOut'
    }
    // 3. confirm回调
    onConfirm: function(){
        console.log('ok')
    },
    // 4. cancel糊掉
    onCancel: function(){
        console.log('cancel')
    // }
})
  • 方法调用

    1. 显示弹窗
    2. 关闭弹窗

代码实现

modal.show(/* 可以传入内容 */);
modal.hide();

这里使用的是TDD思想,行为驱动开发,先定义使用方式,再去开发

实现思路

宏观的角度去思考有哪些业务逻辑,首先构建

function Modal(){
}
Modal.prototype.show=function(){
    //显示逻辑
};
Modal.prototype.show=function(){
    //隐藏逻辑
};

在Modal对象里去配置实例的私有变量,最后执行初始化事件绑定。

function Modal(options){
options = options || {};

// 即 div.m-modal 节点
//每个Modal被示例后都应该是独立的,所以我们需要复制传入的目标节点
this.container = this._layout.cloneNode(true);

// body 用于插入自定义内容
this.body = this.container.querySelector('.modal_body');

// 窗体节点,在应用动画时有用
this.wrap = this.container.querySelector('.modal_wrap');

// 将options 复制到 组件实例上
extend(this, options);

this._initEvent();
}
// 显示弹窗
extend(Modal.prototype,
    show: function(content){
      //如果传入内容久设置内容
      if(content) this.setContent(content);
    
      document.body.appendChild(this.container);
      animateClass(this.wrap, this.animation.enter)
    
    
    },
    hide: function(){

      var container = this.container;

      animateClass(this.wrap, this.animation.leave, function(){
        document.body.removeChild(container);
      })
      
    }
}

组件完善

  1. 一个组件写好之后肯定是希望它能在尽可能多的地方被使用,所以模块化非常重要。多个团队如果存在使用不同的模块管理工具的情况,我们就需要在暴露接口的时候做好兼容
// 支持commonjs
if (typeof exports === 'object') {
    module.exports = Modal;
// 支持amd
} else if (typeof define === 'function' && define.amd) {
    define(function() {
    return Modal
});
} else {
    // 直接暴露到全局
    window.Modal = Modal;
}
  1. react给了我一个思路就是将HTML装入js。这样别人需要用到我做好的组件时,只需要引入js包,不必再跑到html文件里去复制结构
var template = 
'
\ \ \
';

把节点用字符串方式拼接,然后再插入到DOM中

// 将HTML转换为节点
function html2node(str){
    var container = document.createElement('div');
    container.innerHTML = str;
    return container.children[0];
}

这样别人只需要引入js文件就能获得我写好的组件。

当然复杂的组件对于结构的拼接要更复杂,react的JSX很好用,同时兼具react的diff算法,能快速计算出需要渲染的部分,非常好用。所以组件化也是我推崇react的一个非常关键的原因。

你可能感兴趣的:(react,es6)