react native 日期选择框DatePickerAndr
2019-06-26 本文已影响0人
smallzip


解决方案1
去掉await关键字
// 时间选择框 优化方案1
datePick = () => {
try {
const { action } = DatePickerAndroid.open({
// 要设置默认值为今天的话,使用`new Date()`即可
date: new Date(),
maxDate: new Date(),
minDate: new Date(2018, 3, 1)
}).then(({ year, month, day }) => {
if (action !== DatePickerAndroid.dismissedAction) {
// 这里开始可以处理用户选好的年月日三个参数:year, month (0-11), day
// 取消则不执行
if (year == undefined || year == NaN || month == undefined || month == NaN) {
} else {
ToastAndroid.show(`选择的时间是:${year}-${month + 1}-${day}`, ToastAndroid.SHORT);
}
}
})
} catch ({ code, message }) {}
}
优化方案2
// 时间选择框 优化方案2
datePick1 = async () => {
try {
const {action, year, month, day} = await DatePickerAndroid.open({
// 要设置默认值为今天的话,使用`new Date()`即可。
// 下面显示的会是2020年5月25日。月份是从0开始算的。
date: new Date(2020, 4, 25)
});
if (action !== DatePickerAndroid.dismissedAction) {
// 这里开始可以处理用户选好的年月日三个参数:year, month (0-11), day
ToastAndroid.show(`选择的时间是:${year}-${month + 1}-${day}`, ToastAndroid.SHORT);
}
} catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}

完整deme,可以copy个页面测试
import React, { Component } from 'react';
import { StyleSheet, Text, View, ToastAndroid, DatePickerAndroid } from 'react-native';
export default class Test1 extends Component {
constructor(props) {
super(props);
this.state = {
}
}
// 时间选择框 优化方案1
datePick = () => {
try {
const { action } = DatePickerAndroid.open({
// 要设置默认值为今天的话,使用`new Date()`即可
date: new Date(),
maxDate: new Date(),
minDate: new Date(2018, 3, 1)
}).then(({ year, month, day }) => {
if (action !== DatePickerAndroid.dismissedAction) {
// 这里开始可以处理用户选好的年月日三个参数:year, month (0-11), day
// 取消则不执行
if (year == undefined || year == NaN || month == undefined || month == NaN) {
} else {
ToastAndroid.show(`选择的时间是:${year}-${month + 1}-${day}`, ToastAndroid.SHORT);
}
}
})
} catch ({ code, message }) {}
}
// 时间选择框 优化方案2
datePick1 = async () => {
try {
const {action, year, month, day} = await DatePickerAndroid.open({
// 要设置默认值为今天的话,使用`new Date()`即可。
// 下面显示的会是2020年5月25日。月份是从0开始算的。
date: new Date(2020, 4, 25)
});
if (action !== DatePickerAndroid.dismissedAction) {
// 这里开始可以处理用户选好的年月日三个参数:year, month (0-11), day
ToastAndroid.show(`选择的时间是:${year}-${month + 1}-${day}`, ToastAndroid.SHORT);
}
} catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}
render() {
return (
<View style={styles.container}>
<Text onPress={() => this.datePick()}>时间选择(优化方案1)</Text>
<Text onPress={() => this.datePick1()}>官网时间选择(优化方案2)</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
});