如何使用ReactNative中的DateTimepicker在文本中显示日期?

时间:2019-03-15 07:55:59

标签: react-native

我正在使用DateTimePicker,必须显示一个日期。我要做的是,当用户单击TextView时,DateTimepicker打开并再次在TextView中显示日期。为此,我尝试了以下操作:

DateTimePicker的代码:

constructor(){ 
  super();
  this.state = { 
    PickerValueHolder : '' ,
    isDateTimePickerVisible: false,
    date: 'Birthday'
  }
}

_showDateTimePicker = () => this.setState({ 
  isDateTimePickerVisible: true });
_hideDateTimePicker = () => this.setState({ 
  isDateTimePickerVisible: false});

_handleDatePicked = (date) => {
  this.setState({date: date})
  this._hideDateTimePicker();
};

<TouchableOpacity onPress={this._showDateTimePicker}>
  <Text style={{marginLeft:20}}>{this.state.date}</Text>
</TouchableOpacity>
<DateTimePicker
  isVisible={this.state.isDateTimePickerVisible}
  onConfirm={this._handleDatePicked}
  onCancel={this._hideDateTimePicker/>

1 个答案:

答案 0 :(得分:0)

通过更改以下代码解决了我的问题

 _handleDatePicked = (date) => {
  var date = new Date(date);
  dobValue= isNaN(date) ? this.state.dob :date.getDate() + "/"+ 
  parseInt(date.getMonth()+1) +"/"+ date.getFullYear();
    if (! isNaN(date)) {
    this.setState({ dob: dobValue });
  }
  this._hideDateTimePicker();
  };