-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Scroll.tsx
62 lines (53 loc) · 1.61 KB
/
Scroll.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
/**
* Copyright (c) 2017-present Jared Palmer
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as React from 'react';
import { SharedRenderProps } from '../types';
import { isEmptyChildren } from '../utils';
import { throttle } from '../utils/throttle';
import { supportsPassiveListener } from '../utils/featureDetection';
export interface ScrollProps {
x: number;
y: number;
}
export interface ScrollConfig {
throttle?: number;
}
export class Scroll extends React.Component<
ScrollConfig & SharedRenderProps<ScrollProps>,
ScrollProps
> {
static defaultProps: Partial<ScrollConfig> = {
throttle: 100,
};
state: ScrollProps = { x: 0, y: 0 };
handleWindowScroll = throttle(() => {
this.setState({ x: window.scrollX, y: window.scrollY });
}, this.props.throttle!);
componentDidMount() {
this.handleWindowScroll();
(window as EventTarget).addEventListener(
'scroll',
this.handleWindowScroll,
supportsPassiveListener ? { passive: true } : false
);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleWindowScroll);
}
render() {
const { render, component, children } = this.props;
return component
? React.createElement(component as any, this.state)
: render
? (render as any)(this.state)
: children // children come last, always called
? typeof children === 'function'
? children(this.state)
: !isEmptyChildren(children) ? React.Children.only(children) : null
: null;
}
}