-
-
Notifications
You must be signed in to change notification settings - Fork 921
/
Affix.tsx
109 lines (94 loc) 路 2.61 KB
/
Affix.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import * as React from 'react';
import { PositionProperty } from 'csstype';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { on, getOffset } from 'dom-lib';
import bindElementResize, { unbind as unbindElementResize } from 'element-resize-event';
import { defaultProps } from '../utils';
import { AffixProps } from './Affix.d';
interface Offset {
top?: number;
left?: number;
width?: number;
height?: number;
}
interface AffixState {
offset?: Offset;
fixed?: boolean;
}
class Affix extends React.Component<AffixProps, AffixState> {
static propTypes = {
top: PropTypes.number,
onChange: PropTypes.func
};
static defaultProps = {
top: 0
};
containerRef: React.RefObject<any> = null;
scrollListener = null;
constructor(props) {
super(props);
this.state = {
offset: null,
fixed: false
};
this.containerRef = React.createRef();
}
componentDidMount() {
this.setContainerOffset();
this.scrollListener = on(window, 'scroll', this.updatePosition);
bindElementResize(this.containerRef.current, this.setContainerOffset);
}
componentWillUnmount() {
if (this.scrollListener) {
this.scrollListener.off();
}
if (this.containerRef.current) {
unbindElementResize(this.containerRef.current);
}
}
setContainerOffset = () => {
this.setState(() => {
return { offset: getOffset(this.containerRef.current) };
});
};
updatePosition = () => {
const offset = this.state.offset;
const { top, onChange } = this.props;
const scrollY = window.scrollY || window.pageYOffset;
const fixed = scrollY - (offset.top - top) >= 0;
if (fixed !== this.state.fixed) {
this.setState({ fixed });
onChange?.(fixed);
}
};
render() {
const { classPrefix, children, top, className, style } = this.props;
const { fixed, offset } = this.state;
const classes = classNames(className, {
[classPrefix]: fixed
});
const placeholderStyles = fixed ? { width: offset.width, height: offset.height } : undefined;
const affixStyle = fixed
? {
position: 'fixed' as PositionProperty,
top,
left: offset.left,
width: offset.width,
zIndex: 10,
...style
}
: style;
return (
<React.Fragment>
<div className={classes} style={affixStyle} ref={this.containerRef}>
{children}
</div>
{fixed && <div aria-hidden="true" style={placeholderStyles}></div>}
</React.Fragment>
);
}
}
export default defaultProps<AffixProps>({
classPrefix: 'affix'
})(Affix);