1.安装依赖:
npm i react-native-date-picker --save // 日期选择组件
npm i react-native-modal --save // 模态框组件
2.代码:
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
TouchableOpacity,
View,
Text,
Dimensions,
} from 'react-native';
import DatePicker from 'react-native-date-picker';
import Modal from 'react-native-modal';
const { width } = Dimensions.get('window');
export default class TaskIndex extends Component {
constructor(props) {
super(props);
this.state={
dateTime: new Date(),
modalVisible: false,
}
}
onDateChange = (date) => {
this.setState({
dateTime: date,
});
}
// 取到过去一年的时间
getPassFormatDate = () => {
var nowDate = new Date();
var date = new Date(nowDate);
date.setDate(date.getDate()-30);
var seperator1 = "-";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = year + seperator1 + month + seperator1 + strDate;
return currentdate;
}
close = () => {
this.setState({
modalVisible: false,
})
}
openModal = () => {
this.setState({
modalVisible: true,
})
}
define = () => {
this.close();
const {dateTime} = this.state;
console.log(dateTime);
}
renderContent = () => (
<View style={styles.titleBox}>
<TouchableOpacity
onPress={this.close}
>
<Text style={styles.cancel}>取消</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.define}
>
<Text style={styles.define}>确定</Text>
</TouchableOpacity>
</View>
)
render() {
return (
<SafeAreaView style={{flex:1}}>
<Modal
isVisible={this.state.modalVisible}
style={styles.modalStyle}
onBackdropPress={this.close}
onBackdropPress={this.close}
>
<View style={styles.minBox}>
{this.renderContent()}
<DatePicker
date={this.state.dateTime}
mode='datetime'
placeholder='请选择时间'
minuteInterval={5}
onDateChange={this.onDateChange}
locale="zh"
/>
</View>
</Modal>
<TouchableOpacity
onPress={this.openModal}
>
<Text>openModal</Text>
</TouchableOpacity>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
modalStyle: {
margin: 0,
alignItems:'flex-start',
justifyContent: 'flex-start',
},
minBox: {
position: 'absolute',
backgroundColor: '#fff',
width: width,
height: 300,
position: 'absolute',
right: 0,
left: 0,
bottom: 0,
paddingBottom: 20,
alignItems: 'center',
justifyContent: 'center',
},
titleBox: {
width: width,
paddingVertical: 10,
paddingHorizontal: 16,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
define: {
fontSize: 14,
color: 'blue',
},
cancel: {
fontSize: 14,
color: '#222'
},
});
3.其中DatePicker和Modal的用法有详解:
DatePicker:用法详解:https://blog.csdn.net/Jump_Monkey/article/details/104003501
Modal用法详解:
https://blog.csdn.net/Jump_Monkey/article/details/104003188