ant-design/components/back-top/index.tsx

117 lines
2.6 KiB
TypeScript
Raw Normal View History

2016-07-07 20:25:03 +08:00
import * as React from 'react';
2016-06-23 23:12:18 +08:00
import Animate from 'rc-animate';
import Icon from '../icon';
import addEventListener from 'rc-util/lib/Dom/addEventListener';
import classNames from 'classnames';
2016-07-08 10:23:20 +08:00
import omit from 'object.omit';
2016-06-23 23:12:18 +08:00
function getScroll(w, top) {
let ret = w[`page${top ? 'Y' : 'X'}Offset`];
const method = `scroll${top ? 'Top' : 'Left'}`;
if (typeof ret !== 'number') {
const d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
}
return ret;
}
2016-07-14 13:29:50 +08:00
interface BackTopProps {
visibilityHeight?: number;
onClick?: (event) => void;
prefixCls?: string;
className?: string;
}
2016-06-23 23:12:18 +08:00
2016-07-14 13:29:50 +08:00
export default class BackTop extends React.Component<BackTopProps, any> {
2016-06-23 23:12:18 +08:00
static defaultProps = {
onClick() {},
visibilityHeight: 400,
prefixCls: 'ant-back-top',
2016-07-14 13:29:50 +08:00
};
scrollEvent: any;
2016-06-23 23:12:18 +08:00
constructor(props) {
super(props);
const scrollTop = getScroll(window, true);
this.state = {
visible: scrollTop > this.props.visibilityHeight,
};
}
scrollToTop = (e) => {
2016-07-14 13:29:50 +08:00
if (e) {
e.preventDefault();
}
2016-06-23 23:12:18 +08:00
this.setScrollTop(0);
this.props.onClick(e);
}
setScrollTop(value) {
document.body.scrollTop = value;
document.documentElement.scrollTop = value;
}
handleScroll = () => {
const scrollTop = getScroll(window, true);
this.setState({
visible: scrollTop > this.props.visibilityHeight,
});
}
componentDidMount() {
this.scrollEvent = addEventListener(window, 'scroll', this.handleScroll);
}
componentWillUnmount() {
if (this.scrollEvent) {
this.scrollEvent.remove();
}
}
render() {
2016-07-14 13:29:50 +08:00
const { prefixCls, className, children } = this.props;
2016-06-23 23:12:18 +08:00
const classString = classNames({
[prefixCls]: true,
[className]: !!className,
});
const defaultElement = (
<div className={`${prefixCls}-content`}>
<Icon className={`${prefixCls}-icon`} type="to-top" />
</div>
);
const style = {
display: this.state.visible ? 'block' : 'none',
};
2016-07-08 10:23:20 +08:00
// fix https://fb.me/react-unknown-prop
2016-07-14 13:29:50 +08:00
const divProps = omit(this.props, [
'prefixCls',
'className',
'children',
2016-07-08 10:23:20 +08:00
'visibilityHeight',
]);
2016-06-23 23:12:18 +08:00
return (
<Animate component="" transitionName="fade">
{
this.state.visible ?
<div data-show={this.state.visible} style={style}>
2016-07-08 10:23:20 +08:00
<div {...divProps} className={classString} onClick={this.scrollToTop}>
{children || defaultElement}
</div>
</div>
: null
}
2016-06-23 23:12:18 +08:00
</Animate>
);
}
}