You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-datetime选择器选中值获取异常:text显示undefined求助

Fixing the undefined Value & Displaying Selected Date/Time in react-datetime

Hey there, let's sort out why you're seeing undefined in your console and get that selected date/time showing up in your UI properly.

The Root Cause

The react-datetime library's onChange callback doesn't pass a standard event object with a value property. Instead, it directly passes the selected Date object as the first argument. That's why e.value is returning undefined—you're trying to access a property that doesn't exist on the Date object being passed in.

Step 1: Fix the State Update

Update your updateState method to use the Date object directly, instead of trying to pull a value from it:

updateState(selectedDate) {
  // selectedDate is already the Date object from the picker
  console.log("Selected date:", selectedDate);
  this.setState({ newText: selectedDate }, () => {
    // If you want to log the updated state, do it in the setState callback
    this.showValuee();
  });
}

Note: I moved the showValuee() call into the setState callback because setState is asynchronous—this ensures you're logging the latest state value.

Step 2: Add UI Display for the Selected Date/Time

To show the selected date/time in your UI, add an element in the render method that formats and displays this.state.newText. You can use plain JavaScript Date methods or customize the format to your needs:

import React from 'react';
import '../App.css';
import Datetime from 'react-datetime';

class Datetimepicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      moveaside: false,
      feed_items: [],
      newText: new Date(),
    };
    this.updateState = this.updateState.bind(this);
    this.showValuee = this.showValuee.bind(this);
  }

  updateState(selectedDate) {
    console.log("Selected date:", selectedDate);
    this.setState({ newText: selectedDate }, this.showValuee);
  }

  showValuee() {
    console.log("Current state date:", this.state.newText);
  }

  // Helper function to format the date for readable UI display
  formatDate(date) {
    // Uses the user's local date/time format by default
    return date.toLocaleString();
    // Or use a custom format if needed:
    // return `${date.getMonth()+1}/${date.getDate()}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
  }

  render() {
    return (
      <div>
        {/* The datetime picker component */}
        <Datetime 
          className={this.props.show ? 'rdt' : 'hide'} 
          onChange={this.updateState} 
          defaultValue={this.state.newText} 
        />
        {/* Display the selected date/time below the picker */}
        <div className="selected-date-display">
          *Selected Date/Time:* {this.formatDate(this.state.newText)}
        </div>
      </div>
    )
  }
}

export default Datetimepicker;

Key Changes Explained

  • updateState: Now accepts the direct Date object from onChange and updates state correctly.
  • setState Callback: Ensures showValuee() runs only after state has been fully updated, avoiding stale state values.
  • formatDate Helper: Converts the raw Date object into a human-readable string for the UI—feel free to tweak the format to match your app's design.
  • UI Display Element: Added a dedicated <div> to show the selected date/time right below the picker, making it visible to users.

Extra Tip

If you want the picker itself to use a specific display format, you can pass the format prop to the Datetime component:

<Datetime 
  className={this.props.show ? 'rdt' : 'hide'} 
  onChange={this.updateState} 
  defaultValue={this.state.newText}
  format="MM/DD/YYYY HH:mm" // Custom format for the picker's internal display
/>

内容的提问来源于stack exchange,提问作者shreyaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:17:23