1 | import React, { Component, } from 'react';
|
2 | import { Dimensions } from 'react-native';
|
3 | import ScrollView from '../ScrollView';
|
4 | import Scene from '../Scene';
|
5 | export class SwiperDefaultProps {
|
6 | constructor() {
|
7 | this.children = [];
|
8 | this.currentPage = 0;
|
9 | }
|
10 | }
|
11 | export class SwiperState {
|
12 | constructor(props) {
|
13 | this.currentPage = props.currentPage;
|
14 | }
|
15 | }
|
16 | const DEVICE_WIDTH = Dimensions.get('window').width;
|
17 | class Swiper extends Component {
|
18 | constructor(props) {
|
19 | super(props);
|
20 | this.state = new SwiperState(this.props);
|
21 | this.getChildren = (children = this.props.children) => React.Children.map(children, child => child);
|
22 | this.goToScene = (nextNumber) => {
|
23 | const currentPage = this.state.currentPage;
|
24 | if (this.onActive[nextNumber]) {
|
25 | this.onActive[nextNumber]();
|
26 | }
|
27 | if (this.onDeactive[currentPage]) {
|
28 | this.onDeactive[currentPage]();
|
29 | }
|
30 | this.setState({ currentPage: nextNumber });
|
31 | };
|
32 | this.renderScene = () => this.getChildren().map(((child, index) => {
|
33 | const key = index;
|
34 | if (typeof child.props.onActive === 'function') {
|
35 | this.bindEvent(this.onActive, key, child.props.onActive);
|
36 | }
|
37 | if (typeof child.props.onDeactive === 'function') {
|
38 | this.bindEvent(this.onDeactive, key, child.props.onDeactive);
|
39 | }
|
40 | return (React.createElement(Scene, { key: child.key, style: [{ width: DEVICE_WIDTH }, child.props.style] }, child));
|
41 | }));
|
42 | this.onActive = [];
|
43 | this.onDeactive = [];
|
44 | }
|
45 | bindOnActive(key, callback) {
|
46 | this.onActive[key] = callback;
|
47 | }
|
48 | bindEvent(obj, key, callback) {
|
49 | const arr = obj;
|
50 | arr[key] = callback;
|
51 | }
|
52 | render() {
|
53 | return (React.createElement(ScrollView, { scrollEnded: this.goToScene, currentPage: 1 }, this.renderScene()));
|
54 | }
|
55 | }
|
56 | Swiper.defaultProps = new SwiperDefaultProps();
|
57 | export default Swiper;
|
58 |
|
\ | No newline at end of file |