react native中利用Picker自定义日期组件(只包含年和月)

因为业务需求,定义只包含年月的日期,react-native自带组件不符合,第三方鸡肋,于是自己写一个,安卓和IOS样式不同,自己体验调用方法示例:
import PickerData from ‘..//Picker‘;
<PickerData  visible={store.visibleReferee}  onCancel={    () => {      store.visibleReferee = false;      return null;    }  }  onRequestClose={    () => {      store.visibleReferee = false;      return null;    }  }  onComfig={(time) => store.comfigTimeReferee(time)}/>
// 传递参数:
visible:  true   false   控制此组件显示和隐藏
// 回调函数
onCancel():  点击取消
onRequestClose(): 物理键返回,此属性不设置会报警告
onComfig(): 点击确认,回调带参数选择的日期 time (2018-02-01)

组件代码:
Picker.js

import React, { PureComponent } from ‘react‘;import {  View,  Picker,  StyleSheet,  Dimensions,  Modal,  TouchableOpacity,  Alert,

  Text 
} from ‘react-native‘;

// 默认获取本地时间const dataObj = new Date();class PickerData extends PureComponent {  constructor(props) {    super(props);// 默认获取显示本地当前时间    this.state = {      datetimeYear: dataObj.getFullYear() + ‘‘,      datetimeMoth: ((dataObj.getMonth() + 1) + ‘‘).length <= 1 ?        (‘0‘ + (dataObj.getMonth() + 1)) : ((dataObj.getMonth() + 1) + ‘‘),    };  }// 生成列表// start 开始时间
// ender 结束时间

// str 日期单位
  _renderDeal = (start, ender, str) => {    const dealRow = [];    for (let i = start; i < ender; i++) {// 月份碰到小于10的加0,例如07月      if ((i + ‘‘).length <= 1) {        dealRow.push(          <Picker.Item label={‘0‘ + i + str} value={‘0‘ + i} key={i} />        );      } else {        dealRow.push(          <Picker.Item label={i + str} value={‘‘ + i} key={i} />        );      }    }    return dealRow;  };

// 格式化日期// 两位数月份  dateFormatting = (temp) => {    const month = (temp.getMonth() + 1) + ‘‘;    if (month.length <= 1) {      return temp.getFullYear() + ‘0‘ + month;    } else {      return temp.getFullYear() + ‘‘ + month;    }  };

// 点击确认回调方法onComfig
  comfig = () => {    const yeartime = this.dateFormatting(dataObj);    const yeartimeer = this.state.datetimeYear + this.state.datetimeMoth;// 用户点错月份      if (yeartime < yeartimeer) {      Alert.alert(‘错误提示‘, ‘当月没有记录,请重新选择日期‘, [{ text: ‘确定‘ }]);    } else {// 回调      this.props.onComfig(yeartimeer);    }  };  render() {    const { visible } = this.props;

return (      <Modal        visible={visible}        transparent={true}        onRequestClose={() => this.props.onRequestClose()}      >        <View style={styles.modelSelect}>          <View style={styles.ViewStyle}>            <View style={{ borderBottomWidth: 1, borderBottomColor: ‘rgb(75,139,249)‘, padding: 20 }}>              <Text style={{ fontSize: 20, color: ‘#000‘ }}>                {this.state.datetimeYear + ‘年‘ + this.state.datetimeMoth + ‘月‘}              </Text>            </View>            <View style={styles.main}>              <Picker                prompt={‘请选择年份‘}                mode="dialog"                selectedValue={this.state.datetimeYear}                onValueChange={(lang) => { this.setState({ datetimeYear: lang }); }}                style={styles.switchStyle}              >                {this._renderDeal(2016, dataObj.getFullYear() + 1, ‘年‘)}              </Picker>              <Picker                prompt={‘请选择月份‘}                mode="dialog"                selectedValue={this.state.datetimeMoth}                onValueChange={(lang) => { this.setState({ datetimeMoth: lang }); }}                style={styles.switchStyle}              >                {this._renderDeal(1, 13, ‘月‘)}              </Picker>            </View>            <View style={{ flexDirection: ‘row‘, borderTopWidth: 1, borderTopColor: ‘rgb(75,139,249)‘ }}>              <TouchableOpacity onPress={() => this.props.onCancel()}>                <View style={[styles.cancelStyle, { borderRightWidth: 1, borderRightColor: ‘rgb(75,139,249)‘ }]}>                  <Text style={{ fontSize: 16 }}>取消</Text>                </View>              </TouchableOpacity>              <TouchableOpacity                onPress={() => { this.comfig(loading); }}              >                <View style={styles.cancelStyle}>                  <Text style={{ fontSize: 16, color: ‘#000‘ }}>确认</Text>                </View>              </TouchableOpacity>            </View>          </View>        </View>      </Modal>

);  }}const styles = StyleSheet.create({  main: {    flex: 1,    flexDirection: ‘row‘,    justifyContent: ‘center‘,    alignItems: ‘center‘,    height: 40,    marginVertical: 20  },  switchStyle: {    width: 140,

},  modelSelect: {    flex: 1,    justifyContent: ‘center‘,    backgroundColor: ‘rgba(0, 0, 0, 0.5)‘,  },  ViewStyle: {    width: Dimensions.get(‘window‘).width - 30,    alignSelf: ‘center‘,    height: __ANDROID__ ? 240 : 300,    justifyContent: ‘center‘,    borderRadius: 10,    marginHorizontal: 15,    backgroundColor: ‘#fff‘  },  cancelStyle: {    justifyContent: ‘center‘,    alignItems: ‘center‘,    height: 60,    width: (Dimensions.get(‘window‘).width - 30) / 2,  }});export default PickerData;

原文地址:https://www.cnblogs.com/zhuyupingit/p/9436471.html

时间: 2024-08-28 02:59:16

react native中利用Picker自定义日期组件(只包含年和月)的相关文章

React Native 中 component 生命周期

React Native 中 component 生命周期 转自 csdn 子墨博客  http://blog.csdn.net/ElinaVampire/article/details/51813677 (非原创) React Native中的component跟Android中的activity,fragment等一样,存在生命周期,下面先给出component的生命周期图 getDefaultProps object getDefaultProps() 执行过一次后,被创建的类会有缓存,映

Facebook React Native 中文教程一:介绍

React Native 中文版 Facebook 在 [React.js Conf 2015](http://conf.reactjs.com/) 大会上推出了基于 JavaScript 的开源框架 [React Native](http://facebook.github.io/react-native/),本中文教程翻译自 [React Native 官方文档](http://facebook.github.io/react-native/docs/getting-started.html

在 React Native 中使用 Redux 架构

前言 Redux 架构是 Flux 架构的一个变形,相对于 Flux,Redux 的复杂性相对较低,而且最为巧妙的是 React 应用可以看成由一个根组件连接着许多大大小小的组件的应用,Redux 也只有一个 Store,而且只用一个 state 树来管理组件的状态.随着应用逐渐变得复杂,React 将组件看成状态机的优势仿佛变成了自身的绊脚石.因为要管理的状态将会越来越多,直到你搞不清楚某个状态在不知道什么时候,由于什么原因,发生了什么变化.Redux 试图让状态的变化变得可预测.Redux

在 React Native 中使用 moment.js 無法載入語系檔案

moment.js 是很常見的日期時間 library,友善的 API 與極佳的執行效率是它的兩大賣點.例如 (new Date()).getFullYear(),如果使用 moment.js 我可以只寫 moment().get('year'),可讀性增強許多. 問題 React Native 0.29.x 預設使用 ES6,並支援 import 語法.問題出在如果遵照官方網站的說明去載入語系檔,會發生找不到模組 (cannot find module) 的錯誤.推測可能是 moment.js

React Native中的网络请求

React Native中的网络请求fetch使用方法最为简单,但却可以实现大多数的网络请求,需要了解更多的可以访问: https://segmentfault.com/a/1190000003810652 /** * Sample React Native App * https://github.com/facebook/react-native * 周少停 2016-09-28 * fetch请求数据 header 参数 response转json 请求方式 */ import React

基于React Native的Material Design风格的组件库 MRN

基于React Native的Material Design风格的组件库.(为了平台统一体验,目前只打算支持安卓) 官方网站 http://mrn.js.org/ Github https://github.com/binggg/mrn 示例应用在线演示 https://appetize.io/app/j48zj9r83cetpd1mhg4g8buc4w 示例应用下载 https://github.com/binggg/MaterialReactNative/blob/master/androi

react native中如何往服务器上传网络图片

1 let common_url = 'http://192.168.1.1:8080/'; //服务器地址 2 let token = ''; //用户登陆后返回的token 3 /** 4 * 使用fetch实现图片上传 5 * @param {string} url 接口地址 6 * @param {JSON} params body的请求参数 7 * @return 返回Promise 8 */ 9 function uploadImage(url,params){ 10 return

react native中Unable to load script from assets &#39;index.android.bundle&#39;解决方案

刚刚朋友问我,说是创建好一个项目,运行后报错:Unable to load script from assets 'index.android.bundle',以前好好的没出现这种现象,于是我找到一个解决方案,分享一下. 解决这个问题的方案是: 进入你该项目的根目录下的 android目录下的app目录下的src文件下的mian文件,(可能说的有点绕),在main件夹下,创建一个assets文件,这个文件是rn的资源文件夹! 之后用dos进入你的项目根目录,执行一下命令: react-nativ

[转] 在React Native中使用ART

http://bbs.reactnative.cn/topic/306/%E5%9C%A8react-native%E4%B8%AD%E4%BD%BF%E7%94%A8art 前半个月捣腾了一下React Native ART 现在手上闲下来了和大家分享一下React Native中的ART使用心得 React Native ART 究竟是什么? 所谓ART,是一个在React中绘制矢量图形的JS类库.这个类库抽象了一系统的通用接口,统一了SVG,canvas,VML这类矢量图形在 React中