react-app-shell
Version:
react打包脚本和example, 这里的版本请忽略
91 lines (83 loc) • 2.85 kB
JavaScript
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import {CSSTransition, TransitionGroup} from 'react-transition-group';
import Notice from './notice';
import styles from './toast.less';
class Notification 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();
if (notices.every(item => item.key !== notice.key)) {
if (notice.length > 0 && notices[notice.length - 1].type === 'loading') {
notices.push(notice);
setTimeout(() => { this.setState({notices}) }, this.transitionTime);
} else {
notices.push(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 (
<TransitionGroup className={styles['toast-notification']}>
{
notices.map(notice => (
<CSSTransition
key={notice.key}
classNames={classNames(styles['toast-notice-wrapper'], styles['notice'])}
timeout={this.transitionTime}
>
<Notice {...notice}/>
</CSSTransition>
))
}
</TransitionGroup>
);
}
}
function createNotification() {
const div = document.createElement('div');
document.body.appendChild(div);
let refNot;
ReactDOM.render(<Notification ref={(node) => { refNot = node }}/>, div);
return {
addNotice(notice) {
return refNot.addNotice(notice);
},
destroy() {
ReactDOM.unmountComponentAtNode(div);
document.body.removeChild(div);
}
};
}
export default createNotification();