自己动手写一个滚动的日期选择器(react native)

效果图
自己动手写一个滚动的日期选择器(react native)_第1张图片

import React, { Component } from 'react'
import { ScrollView, Text, View, StyleSheet } from 'react-native';
import { scaleSize, screenWidth } from '../../utils/AdaptUtil'
export default class ScrollPicker extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedValue: props.selectedValue || [],
            pickData: props.pickData || []
        };
    }
    onMomentumScrollBegin = ({ nativeEvent }) => {
        console.warn("onMomentumScrollBegin", nativeEvent);
    }

    onMomentumScrollEnd = (index, { nativeEvent }) => {
        let { selectedValue } = this.state
        let unitHeight = scaleSize(148)
        let { contentOffset } = nativeEvent
        let offsetY = contentOffset.y
        let scrollIndex = Math.round(offsetY / unitHeight)
        selectedValue[index] = scrollIndex
        this.setState({
            selectedValue
        })
        this[`refs${index}`].scrollTo({ x: 0, y: unitHeight * scrollIndex, animated: true })
    }

    onLayout = () => {
        let unitHeight = scaleSize(148)
        let { selectedValue } = this.state
        selectedValue.forEach((item, index) => {
            this[`refs${index}`].scrollTo({ x: 0, y: unitHeight * item, animated: true })
        })
    }

    renderSelectColumn = (list, index) => {
        let width = screenWidth / this.state.pickData.length - scaleSize(30)
        return (
            
                 {
                        this[`refs${index}`] = node
                    }}
                    onLayout={this.onLayout}
                    showsVerticalScrollIndicator={false}
                    onMomentumScrollBegin={this.onMomentumScrollBegin}
                    onMomentumScrollEnd={this.onMomentumScrollEnd.bind(this, index)}
                >
                    
                    {
                        list.map((item, index1) => {
                            return (
                                {item}
                            )
                        })
                    }
                    
                
            
        )
    }

    render() {
        return (
            
                
                
                
                    {
                        this.state.pickData.map((item, index) => {
                            return (this.renderSelectColumn(item, index))
                        })
                    }
                
            
        )
    }
}

你可能感兴趣的:(自己动手写一个滚动的日期选择器(react native))