react实现提示消息容器,可以动态添加,删除内部子提示消息
import React, { useState, useRef, useEffect } from 'react' import PropTypes from 'prop-types' import _ from 'lodash' import uuidv1 from 'uuid/v1' import './index.less' let currentTipComponents = [] let setCurrentTipComponents function GlobalTipContainer(props) { const { style } = props const wrapperStyle = _.assign({}, style) const [tipComponents, setTipComponents] = useState([]) currentTipComponents = tipComponents setCurrentTipComponents = setTipComponents const [displayedTipComponents, setDisplayedTipComponents] = useState([]) const [mouseHover, setMouseHover] = useState(false) const wrapElemRef = useRef(null) useEffect(() => { if (mouseHover === false) { wrapElemRef.current.scrollTop = 10e10 } }) useEffect(() => { setDisplayedTipComponents(tipComponents.slice(0, 2)) }, [tipComponents]) return ( <div className="global-tip-container-component-wrap" ref={wrapElemRef} onMouseEnter={() => { setMouseHover(true) }} onMouseLeave={() => { setMouseHover(false) }} style={wrapperStyle} > {displayedTipComponents} </div> ) } GlobalTipContainer.addTip = (tipComponent) => { const key = uuidv1() currentTipComponents = currentTipComponents.slice(0) currentTipComponents.push(React.cloneElement(tipComponent, { key, onClose: _.flow(tipComponent.props.onClose || _.noop, () => { GlobalTipContainer.removeTip(key) }), })) setCurrentTipComponents(currentTipComponents) return key } GlobalTipContainer.removeTip = (key) => { const index = _.findIndex(currentTipComponents, ['key', key]) if (index !== -1) { currentTipComponents.splice(index, 1) setCurrentTipComponents(currentTipComponents.slice(0)) } } GlobalTipContainer.propTypes = { style: PropTypes.object, } GlobalTipContainer.defaultProps = { style: {}, } export default GlobalTipContainer