React Native:你如何实现DatePickerAndroid?

时间:2016-07-06 05:33:51

标签: javascript reactjs native

根据RN文档,您必须调用async / await函数来打开Android Date Picker。我已经尝试将Async安装到生成器转换Babel预设并添加带有

的.babelrc文件

{ "plugins": ["transform-async-to-generator"] }

但是,当使用标签添加任何RN组件时,这似乎会引发意外的令牌错误(例如< Image ... />会抛出并出现意外的令牌错误)。这就是我打开Android Date Picker的功能

async openAndroidDatePicker: function() {
  try {
    const {action, year, month, day} = await DatePickerAndroid.open({
      date: new Date()
    });
  } catch ({code, message}) {
    console.warn('Cannot open date picker', message);
  }
}

4 个答案:

答案 0 :(得分:4)

解决。我的函数的语法错了......这对我有用:

async openAndroidDatePicker() {
  try {
    const {action, year, month, day} = await DatePickerAndroid.open({
      date: new Date()
    });
  } catch ({code, message}) {
    console.warn('Cannot open date picker', message);
  }
}

请记住,我在这个例子中使用了createClass,而不是es6类。

答案 1 :(得分:4)

我的方式没有任何软件包,仅使用文档DatePickerAndroidTimePickerAndroid

导入所需组件。对我来说是:

import {
Text,
SafeAreaView,
TouchableOpacity,
View,
Platform,
StatusBar,
DatePickerIOS,
Slider,
DatePickerAndroid,
TimePickerAndroid,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import MainStyles from '../styles/MainStyles';

然后设置您的状态:

constructor(props) {
 super(props);
 this.setDate = this.setDate.bind(this);
 this.state = {
   chosenDate: new Date(),
   chosenAndroidTime: '00:00',
   androidDate: `${new Date().getUTCDate()}/${new Date().getUTCMonth() + 1}/${new Date().getUTCFullYear()}`,
   value: 50,
 };
}

声明函数后:

setDate(newDate) {
  this.setState({ chosenDate: newDate });
}

setDateAndroid = async () => {
  try {
    const {
      action, year, month, day,
    } = await DatePickerAndroid.open({
    date: new Date(),
    minDate: new Date(),
    });
    if (action !== DatePickerAndroid.dismissedAction) {
      this.setState({ androidDate: `${day}/${month + 1}/${year}` });
    }
  } catch ({ code, message }) {
    console.warn('Cannot open date picker', message);
  }
};

setTimeAndroid = async () => {
  try {
    const { action, hour, minute } = await TimePickerAndroid.open({
      hour: 14,
      minute: 0,
      is24Hour: false, // Will display '2 PM'
    });
    if (action !== TimePickerAndroid.dismissedAction) {
      // Selected hour (0-23), minute (0-59)
      const m = (minute < 10) ? `0${minute}` : minute;
      const h = (hour < 10) ? `0${hour}` : hour;
      console.log(`time: ${hour}:${minute}`);
      this.setState({ chosenAndroidTime: `${h}:${m}` });
    }
  } catch ({ code, message }) {
    console.warn('Cannot open time picker', message);
  }
};

最后添加到您的视图容器:

       {
          Platform.OS === 'ios' ? (
            <DatePickerIOS
              date={chosenDate}
              onDateChange={this.setDate}
            />
          ) : (
            <View style={MainStyles.AndroidDatePickerWrap}>
              <TouchableOpacity onPress={() => this.setDateAndroid()}>
                <View style={MainStyles.HistoryTime}>
                  <Icon name="ios-calendar" size={25} color="rgb(49, 49, 49)" />
                  <Text style={[MainStyles.HistoryTimeText, { fontSize: 16 }]}>
                    {androidDate}
                  </Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => this.setTimeAndroid()}>
                <View style={MainStyles.HistoryTime}>
                  <Icon name="ios-time" size={25} color="rgb(49, 49, 49)" />
                  <Text style={[MainStyles.HistoryTimeText, { fontSize: 16 }]}>
                    {chosenAndroidTime}
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
          )
        }

因此,您必须看到iOS和android的不同选择器。 这对我有用,希望对您有帮助。

答案 2 :(得分:3)

我在我的应用程序中使用了一个用于日期选择器android的库。 检查样品的使用情况:

'use-strict';

import React, {Component} from 'react'
import{
  StyleSheet,
  View,
  Text,
  Image,
  TextInput,
  Dimensions,

}from 'react-native';

import DatePicker from 'react-native-datepicker';
var {width,height} = Dimensions.get('window');

class Booking extends Component{

  constructor(props) {
  super(props);
  this.state = {

  date_in: '2016-05-01',
  date_out: '2016-05-01',

 };
}

 render(){

return(
  <View>

  <Text style={{fontSize:18, marginLeft:10, marginTop:10}}>Arrival/Departure:</Text>

  <DatePicker
      style ={{padding:10}}
      date={this.state.date_in}
      mode="date"
      format="YYYY-MM-DD"
      minDate="2016-05-01"
      maxDate="2016-06-01"
      showIcon={false}
      customStyles={{
       dateInput: {
          alignItems : 'flex-start',
          padding:5
      },
     }}
    onDateChange={(date_in) => {this.setState({date_in: date_in});}}/>

  </View>
);
}
}


var styles = StyleSheet.create({

  picker: {
   width: 100,
  },
 });

 module.exports = Booking;

有关详细信息,请参阅此处:

Date picker react native

希望这可以帮助你:)

答案 3 :(得分:0)

只需在您的DatePicker按钮之一上调用此函数

openDatePicker() {
    try {
      DatePickerAndroid.open({
        date: new Date()
      }).then(date => {
        if (date.action !== DatePickerAndroid.dismissedAction) {
          //Please take note that the number of the months is based on 
          //the count of an index, let say January is 0, February is 1 and so on...
          //if you want the count to be  1 to 12 for months, then add 1

          const finalDate = `${date.month + 1} ${date.day} ${date.year}`;
          console.log(finalDate)

          //Let say i pick February 10 2019, the output will be 2 10 2019
          //You can use moment to format the date as you like 

          //Here's an example:
          //console.log(moment(finalDate, 'MM DD YYYY').format('LL'))
          //Output: February 10, 2019
        }
      });
    } catch ({ code, message }) {
      console.warn('Cannot open date picker', message);
    }
  }