Get selected date from ReactNative-DatePickerAndro

2020-07-26 03:12发布

问题:

I am following ReactNative DatePickerAndroid Docs. For DatePickerIOS we have onDateChange method.

Is there any similar method to get selected date from DatePickerAndroid? Above documentation didn't mention any code example to get selected date.

回答1:

You can get selected date in showPicker method from given code example :

showPicker = async (stateKey, options) => {
    try {
      var newState = {};
      const {action, year, month, day} = await DatePickerAndroid.open(options);
      if (action === DatePickerAndroid.dismissedAction) {
        newState[stateKey + 'Text'] = 'dismissed';
      } else {
        // <<<< Newly selected date >>>>
        var date = new Date(year, month, day);
        newState[stateKey + 'Text'] = date.toLocaleDateString();
        newState[stateKey + 'Date'] = date;
      }
      this.setState(newState);
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  };
render() {
   return (
   <TouchableWithoutFeedback
    onPress={this.showPicker.bind(this, 'spinner', { date: this.state.presetDate })}>
     <View>
        <Text style={styles.text}>Date selector</Text>
     </View>
   </TouchableWithoutFeedback>
  )
}


回答2:

As we can see the example code on documentation, create an async function, this function will handle promise data, and trigger this function to you component Text with onPress function or TexInput with onFocus function. example:

async _onMyDatePress(){
   try {
            const {action, year, month, day} = await DatePickerAndroid.open({           
                date: new Date()
            });

            if(action == DatePickerAndroid.dateSetAction){
                console.log(year + ' ' + month + ' ' + day);
            }

        } catch ({code, message}) {
            console.warn('Cannot open date picker', message);
        }   
}