【问题标题】:React Native: How do you implement DatePickerAndroid?React Native:你如何实现 DatePickerAndroid?
【发布时间】:2016-07-06 05:33:50
【问题描述】:

根据 RN 文档,您必须调用 async/await 函数才能打开 Android 日期选择器。我已经尝试安装 Async 到生成器转换 Babel 预设并添加一个带有

的 .babelrc 文件

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

但是,当使用标签添加任何 RN 组件时,这似乎会引发意外的标记错误(例如, 会引发意外的标记错误)。这就是我打开 Android 日期选择器的功能的样子

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);
  }
}

【问题讨论】:

    标签: javascript reactjs native


    【解决方案1】:

    我的方式没有任何包,只使用文档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 的不同选择器。 这对我有用,希望对你有帮助。

    【讨论】:

    • 这是一个很好的解决方案。确保将 {androidDate} 更改为 {this.state.androidDate}。与 {chosenAndroidTime} 类似。
    • @Serj 这是您可以为 DatePicker 和 TimePicker 获得的最好和最简单的解决方案。感谢您分享解决方案,它真的很好用:)
    【解决方案2】:

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

    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 类。

    【讨论】:

      【解决方案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

      希望对你有帮助:)

      【讨论】:

      • 你能使用 RN Core 的 DatePickerAndroid API 吗?
      • 我还没有使用过 RN Cores DatePickerAndroid.. 因为库的实现非常简单......
      【解决方案4】:

      只需在一个 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);
          }
        }
      

      【讨论】:

        猜你喜欢
        • 2022-12-09
        • 2015-10-16
        • 1970-01-01
        • 2017-12-29
        • 2015-05-31
        • 1970-01-01
        • 2015-07-30
        • 2017-07-06
        • 2017-02-26
        相关资源
        最近更新 更多