react-native DatePicker日期选择组件的实现代码

发布时间:2020-09-20 05:21:19 作者:Agent_Skye
来源:脚本之家 阅读:255

本教程的实现效果如下:

react-native DatePicker日期选择组件的实现代码

为了实现其淡入/淡出的覆盖效果, 还有取消按钮, 在此用了一个三方的组件, 大家可以先安装一下:

三方组件的地址:https://github.com/eyaleizenberg/react-native-custom-action-sheet (可以看看,也可以直接按我的步骤走)

1. 在terminal的该工程目录下运行: npm install react-native-custom-action-sheet --save
2. 然后运行: npm start
3. 具体实现代码如下:

import React, { Component } from 'react'; 
import { 
 AppRegistry, 
 StyleSheet, 
 Text, 
 View, 
 TouchableHighlight, 
 DatePickerIOS 
} from 'react-native'; 
 
//这是一个三方组件 github地址:https://github.com/eyaleizenberg/react-native-custom-action-sheet 
var CustomActionSheet = require('react-native-custom-action-sheet'); 
 
class Demo extends Component { 
 
 state = { 
  datePickerModalVisible: false, //选择器显隐标记 
  chooseDate: new Date() //选择的日期 
 }; 
 
 _showDatePicker () { //切换显隐标记 
  this.setState({datePickerModalVisible: !this.state.datePickerModalVisible}); 
 }; 
 
 _onDateChange (date) { //改变日期state 
  alert(date); //弹出提示框: 显示你选择日期 
  this.setState({ 
   chooseDate: date 
  }); 
 }; 
 
 render() { 
 
  let datePickerModal = (  //日期选择器组件 (根据标记赋值为 选择器 或 空) 
   this.state.datePickerModalVisible ? 
   <CustomActionSheet 
    modalVisible={this.state.datePickerModalVisible} //显隐标记 
    onCancel={()=>this._showDatePicker()}> //点击取消按钮 触发事件 
     <View style={styles.datePickerContainer}> 
      <DatePickerIOS 
       mode={"datetime"}  //选择器模式: 'date'(日期), 'time'(时间), 'datetime'(日期和时间) 
       minimumDate={new Date()} //最小时间 (这里设置的是当前的时间) 
       minuteInterval={30} //最小时间间隔 (这里设置的是30分钟) 
       date={this.state.chooseDate} //默认的时间 
       onDateChange={this._onDateChange.bind(this)} //日期被修改时回调此函数 
      /> 
      </View> 
    </CustomActionSheet> : null 
  ); 
 
  return ( 
   <View style={styles.container}> 
    <TouchableHighlight 
     style={{backgroundColor:'cyan', padding:5}} 
     onPress={()=>this._showDatePicker()} //按钮: 点击触发方法 
     underlayColor='gray' 
     > 
     <Text >show DatePick</Text> 
    </TouchableHighlight> 
    {datePickerModal} //日期选择组件 
   </View> 
  ); 
 } 
} 
 
const styles = StyleSheet.create({ 
 container: { 
  flex: 1, 
  justifyContent: 'center', 
  alignItems: 'center', 
  backgroundColor: '#F5FCFF', 
 }, 
 datePickerContainer: { 
  flex: 1, 
  borderRadius: 5, 
  justifyContent: 'center', 
  alignItems: 'center', 
  backgroundColor: 'white', 
  marginBottom: 10, 
 }, 
}); 
 
AppRegistry.registerComponent('Demo', () => Demo); 

写好了,在terminal中运行:react-native run-ios 就能看到效果了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. React JS和React-Native学习指南
  2. React-Native组件之ListView

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

react native 日期

上一篇:SpringCloud URL重定向及转发代码实例

下一篇:JavaScript模板引擎实现原理实例详解

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》