1 | import React, { Component, } from 'react';
|
2 | import { Dimensions, ScrollView, } from 'react-native';
|
3 | import Animate from './Animate';
|
4 | const DEVICE_WIDTH = Dimensions.get('window').width;
|
5 | const NOOP = () => { };
|
6 | export class HScrollViewDefaultProps {
|
7 | constructor() {
|
8 | this.currentPage = 0;
|
9 | this.scrollEnded = NOOP;
|
10 | this.children = null;
|
11 | }
|
12 | }
|
13 | export class HScrollViewDefaultState {
|
14 | constructor(props, width) {
|
15 | this.currentPage = props.currentPage;
|
16 | this.containerWidth = width;
|
17 | }
|
18 | }
|
19 | class HScrollView extends Component {
|
20 | constructor(props) {
|
21 | super(props);
|
22 | this.scrollEnded = (event) => {
|
23 | const position = event.nativeEvent.contentOffset.x;
|
24 | const currentPage = position / DEVICE_WIDTH;
|
25 | if (currentPage !== this.state.currentPage) {
|
26 | this.scrollToItem(currentPage);
|
27 | this.setState({ currentPage });
|
28 | this.props.scrollEnded(currentPage);
|
29 | }
|
30 | };
|
31 | this.scrollToItem = (itemIndex) => {
|
32 | const scrollToX = itemIndex * DEVICE_WIDTH;
|
33 | setTimeout(() => {
|
34 | if (!!this.screen) {
|
35 | this.screen.scrollTo({ y: 0, x: scrollToX, animated: true });
|
36 | }
|
37 | }, 0);
|
38 | };
|
39 | this.state = new HScrollViewDefaultState(this.props, DEVICE_WIDTH);
|
40 | }
|
41 | componentWillReceiveProps(nextProps) {
|
42 | if (this.props.currentPage !== nextProps.currentPage) {
|
43 | this.scrollToItem(nextProps.currentPage);
|
44 | }
|
45 | }
|
46 | render() {
|
47 | return (React.createElement(ScrollView, { ref: (ref) => { this.screen = ref; }, horizontal: true, scrollEnabled: true, pagingEnabled: true, scrollEventThrottle: 500, removeClippedSubviews: true, showsHorizontalScrollIndicator: false, automaticallyAdjustContentInsets: true, onMomentumScrollEnd: this.scrollEnded }, this.props.children));
|
48 | }
|
49 | }
|
50 | HScrollView.defaultProps = new HScrollViewDefaultProps();
|
51 | HScrollView.Animate = Animate;
|
52 | export default HScrollView;
|
53 |
|
\ | No newline at end of file |