如何用react封装一款Toast 控件

2,157 阅读1分钟

这是我参与11月更文挑战的第13天,活动详情查看:2021最后一次更文挑战

TIP 👉 呜呼!楚虽三户能亡秦,岂有堂堂中国空无人!____陆游《金错刀行》

前言

Web Component是前端界一直非常热衷的一个领域,用第三方组件化的框架去实现的话,你需要依赖框架本身很多东西,很多时候我们只是简单的几个组件,不是很大,也不是很多,所以为了保证组件的`轻量,简单`,其实这个时候我们并不想采用第三方的框架。

Toast 控件

import

import Toast from '@/components/Toast/index';

Props

无 (组件无props,逻辑控制在index.js里面)

用法如下

参数详情
  • content:提示自定义信息,默认是有 '操作成功'、'加载中...'
  • duration:自定义toast关闭时间,默认是2000
  • onClose:true/false 是否关闭标识
Toast.info(content, duration, onClose)
Toast.success(content, duration, onClose)
Toast.error(content, duration, onClose)
Toast.loading(content, duration, onClose)
import React, { Component } from 'react'
import './Toast.scss'

class ToastBox extends Component {
  constructor() {
    super()
    this.transitionTime = 300
    this.state = { notices: [] }
    this.removeNotice = this.removeNotice.bind(this)
  }

  getNoticeKey() {
    const { notices } = this.state
    return `notice-${new Date().getTime()}-${notices.length}`
  }

  addNotice(notice) {
    const { notices } = this.state
    notice.key = this.getNoticeKey()

    // notices.push(notice);//展示所有的提示
    notices[0] = notice;//仅展示最后一个提示

    this.setState({ notices })
    if (notice.duration > 0) {
      setTimeout(() => {
        this.removeNotice(notice.key)
      }, notice.duration)
    }
    // return () => { this.removeNotice(notice.key) }
  }

  removeNotice(key) {
    const { notices } = this.state
    this.setState({
      notices: notices.filter((notice) => {
        if (notice.key === key) {
          if (notice.onClose) setTimeout(notice.onClose, this.transitionTime)
          return false
        }
        return true
      })
    })
  }

  render() {
    const { notices } = this.state
    return (
      <div className="toast">
        {
          notices.map(notice => (
            <div className="toast_bg" key={notice.key}>
              <div className='toast_box'>
                <div className='toast_text'>{notice.content}</div>
              </div>
            </div>
          ))
        }
      </div>
    )
  }
}

export default ToastBox

样式这块就先不放了

「欢迎在评论区讨论」

希望看完的朋友可以给个赞,鼓励一下