React实现单例组件

问题背景

在工作中遇到了这样一个场景,写了个通用的弹窗组件,却在同一个页面中多次使用了该组件。当点击打开弹窗时,可想而知,一次性打开了多个弹窗,而业务需求只需要打开一个。

我个人在解决问题过程中的一些已废弃思路

我首先想到的是能不能像mobx的@observer一样用一个譬如@singleton来修饰组件类,然后在像正常组件一样在使用组件的地方使用标签名来使用该组件。google了大半小时,发现行不通,因为每在render方法里使用一个组件,React就会自动实例化一个组件类,所以React本身的设计其实完全不适用于单例

解决问题的核心思路

  1. 采用类似调用方法的形式而非组件标签的形式来调用组件
  2. 只能在一个特定的容器内render组件,从而保证单例

代码


import React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
//具体单例类代码
export default class Singleton {
  constructor(component){
    this.dom = null;
    this.component = component;
    this.instance = null;
  }

  render(option) {
    if(!this.dom) {
      this.dom = document.createElement('div');
      document.body.appendChild(this.dom);
    }
    this.instance = ReactDOM.render(<this.component {...option}/>, this.dom);
  }

  destroy() {
    unmountComponentAtNode(this.dom);
  }
}

//使用例子
//在适当地方调用如下代码渲染组件
new Singleton(Component).show();
posted @ 2018-03-12 21:45  晚安呢太阳  阅读(3719)  评论(0编辑  收藏  举报