-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
63 lines (51 loc) · 1.81 KB
/
index.js
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
import React, { useState, useImperativeHandle, useRef } from 'react';
import SnapScrollView from './SnapScrollView';
let snapPointsHolder = {};
const SV = React.forwardRef(({ children, snapPoints: propsSnapPoints, ...props }, ref) => {
const [snapPoints, setSnapPoints] = useState([]);
const scrollViewRef = useRef(null);
const onLayout = (event, index) => {
const { layout } = event.nativeEvent;
snapPointsHolder = { ...snapPointsHolder, [index]: Math.round(layout.y) };
setSnapPoints(Object.values(snapPointsHolder).map(point => parseInt(point, 10)));
};
useImperativeHandle(ref, () => ({
onLayout: (event, index) => {
onLayout(event, index);
},
scrollTo: args => {
scrollViewRef.current.scrollTo(args);
},
}));
const recursiveMap = ch =>
React.Children.map(ch, child => {
if (!React.isValidElement(child)) {
return child;
}
if (child.props.children) {
child = React.cloneElement(child, {
children: recursiveMap(child.props.children),
});
}
if (child.props.setSnapPoint) {
return React.cloneElement(child, {
...child.props,
onLayout: event => onLayout(event, child.key),
});
}
return child;
});
const content = React.Children.map(children, child =>
child ? React.cloneElement(recursiveMap(child)[0]) : null
);
return (
<SnapScrollView
ref={scrollViewRef}
{...props}
snapPoints={propsSnapPoints || snapPoints}
>
{content}
</SnapScrollView>
);
});
export default SV;