项目中经常会用到类似安卓的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);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。