美文网首页
react-native 自定义简单日历组件

react-native 自定义简单日历组件

作者: 俗人彭jin | 来源:发表于2019-03-03 10:22 被阅读0次

    react-native 自定义简单日历组件

    先yarn add moment 只依赖这个日期处理插件

    import { Component } from "react";
    
    /**
     * 日历组件
     */
    var React = require('react');
    var ReactNative = require('react-native');
    
    var {
        StyleSheet,
        View,
        Text,
        ListView,
        TouchableOpacity,
        Dimensions
    } = ReactNative;
    
    import moment from 'moment';
    import lodash from 'lodash';
    import PropTypes from 'prop-types';
    
    
    const width = Dimensions.get('window').width
    const height = Dimensions.get('window').height
    
    class DateInfo extends Component {
        constructor(props) {
            super(props);
            var ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
            this.state = {
                dataSource: ds.cloneWithRows(['row 1', 'row 2']),
                tmpDataSources: [],
                myMonth: moment(new Date()).format('YYYY年MM月'),
            }
        }
        render() {
            return (
                <View style={{ paddingHorizontal: width * 0.05, backgroundColor: this.props.bgColor ? this.props.bgColor : "#ff5754", paddingBottom: 10 }}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingBottom: 12 }}>
                        <TouchableOpacity onPress={this.left} style={styles.leftIcon}>
                            <Text style={{ color: this.props.dayColor ? this.props.dayColor : "#fff", fontSize: 16 }}>上一月 </Text>
                        </TouchableOpacity>
                        <View style={{ width: width * 0.4, height: 34, alignItems: 'center', justifyContent: 'center' }}>
                            <Text style={{ fontSize: 16, color: this.props.dayColor ? this.props.dayColor : "#fff" }}>{this.state.myMonth}</Text>
                        </View>
                        <TouchableOpacity onPress={this.right} style={styles.leftIcon}>
                            <Text style={{ color: this.props.dayColor ? this.props.dayColor : "#fff", fontSize: 16 }}>下一月</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={{ flexDirection: 'row', paddingBottom: 10 }}>
                        <Text style={[styles.line, { color: this.props.headTextColor }]}>一</Text>
                        <Text style={[styles.line, { color: this.props.headTextColor }]}>二</Text>
                        <Text style={[styles.line, { color: this.props.headTextColor }]}>三</Text>
                        <Text style={[styles.line, { color: this.props.headTextColor }]}>四</Text>
                        <Text style={[styles.line, { color: this.props.headTextColor }]}>五</Text>
                        <Text style={[styles.line, { color: this.props.headTextColor }]}>六</Text>
                        <Text style={[styles.line, { color: this.props.headTextColor }]}>日</Text>
                    </View>
                    <View style={{ color: this.props.bgColor, width: width }}>
                        <ListView dataSource={this.state.dataSource}
                            pageSize={7}
                            contentContainerStyle={{ flexDirection: 'row', flexWrap: 'wrap', width: width }}
                            renderRow={(rowData, sectionId, rowId) =>
                                <View style={styles.row}>
                                    {
                                        rowData.isSelected ?
                                            <TouchableOpacity
                                                onPress={() => this.myClickDate(rowId)}
                                                style={[styles.littleRow, { backgroundColor: this.props.activeBgColor }]}>
                                                <Text style={{ color: this.props.activeTextColor }}>{rowData.id}</Text>
                                            </TouchableOpacity>
                                            :
                                            <TouchableOpacity
                                                onPress={() => this.myClickDate(rowId)}
                                                style={[styles.littleRow]}>
                                                <Text style={{ color: this.props.textColor }}>{rowData.id}</Text>
                                            </TouchableOpacity>
                                    }
                                </View>
                            }
                        />
                    </View>
                </View>
            )
        }
        componentDidMount() {
            this.monthDay(moment(new Date()).format('YYYY-MM-DD'))
        }
        monthDay = (date) => {
            var daysArr = [];
            var currentWeekday = moment(date).date(1).weekday(); // 获取当月1日为星期几
            var currentMonthDays = moment(date).daysInMonth(); // 获取当月天数
            if (currentWeekday == 0) { //如果是0的话就是周日
                currentWeekday = 7;
            }
            for (var i = 1; i < currentWeekday; i++) {
                daysArr.push({ id: '' })
            }
            var YYMM = moment(date, 'YYYY-MM-DD').format('YYYYMM')
            var nowDate = moment(new Date()).format('YYYYMMDD');
            for (var i = 1; i <= currentMonthDays; i++) {
                var myDate = moment(YYMM + i, 'YYYYMMD').format('YYYYMMDD')
                console.log(moment(nowDate).diff(myDate, 'days') == 0, moment(new Date).date())
                if (moment(new Date).date() === moment(myDate, 'YYYYMMDD').date()) { // 当天
                    // 选中当日 暂时写false
                    daysArr.push({ id: i, isSelected: false })
                } else {
                    daysArr.push({ id: i })
                }
            }
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(daysArr),
                tmpDataSources: daysArr
            })
            console.log(daysArr)
        }
        left = () => {
            this.setState({
                myMonth: moment(this.state.myMonth, 'YYYY年MM月').subtract('month', 1).format('YYYY年MM月')
            })
            this.monthDay(moment(this.state.myMonth, 'YYYY年MM月').subtract('month', 1).format('YYYY-MM-DD'))
        }
        right = () => {
            this.setState({
                myMonth: moment(this.state.myMonth, 'YYYY年MM月').add('month', 1).format('YYYY年MM月')
            })
            this.monthDay(moment(this.state.myMonth, 'YYYY年MM月').add('month', 1).format('YYYY-MM-DD'))
        }
        myClickDate = (index) => {
            let { tmpDataSources } = this.state;
            tmpDataSources.forEach((item) => {
                item.isSelected = false;
            })
            tmpDataSources[index].isSelected = true;
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(lodash.cloneDeep(tmpDataSources)),
                tmpDataSources
            })
            console.log(tmpDataSources, moment(new Date()).day())
    
            this.props.callback(tmpDataSources[index]);
    
    
        }
    
    }
    const styles = StyleSheet.create({
        line: {
            flex: 1,
            textAlign: 'center',
            color: '#ff8c87'
        },
        row: {
            width: width * 0.9 / 7,
            height: width * 0.9 / 7,
            alignItems: 'center',
            justifyContent: 'center',
        },
        littleRow: {
            width: width * 0.1,
            height: width * 0.1,
            alignItems: 'center',
            justifyContent: 'center',
            borderRadius: width * 0.2,
    
        },
        leftIcon: {
            height: 34,
            width: width * 0.3,
            alignItems: 'center', justifyContent: 'center',
        }
    })
    DateInfo.defaultProps = {
        bgColor: '#478bfd',
        headTextColor: '#fff',
        textColor: '#fff',
        activeBgColor: '#fff',
        activeTextColor: '#478bfd'
    }
    DateInfo.PropTypes = {
        bgColor: PropTypes.string.isRequired,
        headTextColor: PropTypes.string.isRequired,
        textColor: PropTypes.string.isRequired,
        activeBgColor: PropTypes.string.isRequired,
        callback: PropTypes.func.isRequired
    }
    
    export default DateInfo
    

    相关文章

      网友评论

          本文标题:react-native 自定义简单日历组件

          本文链接:https://www.haomeiwen.com/subject/ybhpuqtx.html