react封裝一個相似安卓的toast控件message

項目中經常會用到相似安卓的toast的控件。封裝一個如許的組件是每一個項目必需的事變。

import React from 'react';
import ReactDOM from 'react-dom';

let seed = 0;
const now = Date.now();
function getUuid() {
  return `rcNotification_${now}_${seed++}`;
}

class Message extends React.Component {

  constructor(props) {
    super(props);
    this.state = {data: []};
    this.add = this.add.bind(this);
    this.remove = this.remove.bind(this);
  }

  add(notice) {
    console.log('msg123', 'add');
    this.setState({data: [...this.state.data, notice]});
    const that = this;
    setTimeout((() => that.remove(notice.key)), 2000);
  }

  remove(key) {
    console.log('msg123', 'remove');

    const temp = this.state.data.filter(item => {
      const result = item.key != key;
      return result;
    });
    this.setState({data: [...temp]});
  }

  render() {
    console.log('msg123', this.state.data);
    return (
      <div style={{zIndex: 99999, position: 'fixed'}}>
        {
          this.state.data.map(item => {
            if (item.type == 'success') {
              return <div className="lcx_hint" key={item.key} style={{position: 'fixed'}}>{item.msg}</div>;
            }
            return <div className="lcx_hint2" key={item.key} style={{position: 'fixed'}}>{item.msg}</div>;
          })
        }
      </div>
    );
  }
}

let instance;
Message.newInstance = function () {

  if (instance) {
    return instance;
  }

  const div = document.createElement('div');
  document.body.appendChild(div);
  const message = ReactDOM.render(<Message />, div);
  console.log('msg123', 'newInstance');
  instance = {
    success(msg) {
      console.log('msg123', 'success');
      message.add({type: 'success', msg, key: getUuid()});
    },
    warning(msg) {
      console.log('msg123', 'warning');
      message.add({type: 'warning', msg, key: getUuid()});
    },
    component: message,
  };
  return instance;
};

export default Message;

封裝完成如許一個組件,詳細使用方法以下:

使用方法:
第一步:

componentWillMount() {
    this.message = Message.newInstance();
 }

第二步須要的處所

 this.message.success('xxx');
 this.message.warning('xxx);
    原文作者:荔枝
    原文地址: https://segmentfault.com/a/1190000015336251
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞