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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值