【问题标题】:ReactJS how to set input Textfield to display current Date and time?ReactJS如何设置输入文本字段以显示当前日期和时间?
【发布时间】:2018-11-09 20:19:42
【问题描述】:

我有一个表单,我想设置一个输入文本字段来显示当前日期和时间:

我有以下功能:

const getDateTime = () => {
  let tempDate = new Date();
  let date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds(); 
  const currDate = "Current Date= "+date;
  return (
     {currDate}
  );
}

对于输入文本字段: 在构造函数中,我设置了状态:

reportStartDate: '',

超文本设置如下:

<div className="form-group">
                <label htmlFor="reportStartDate">Report Start Date:</label>
                <input type="text" name="reportStartDate" className="form-control" placeholder="Report Start Date" value={this.state.reportStartDate} onChange={e => this.change(e)} />
              </div>

如何获取当前日期和时间以显示在文本字段中?

【问题讨论】:

  • 在哪里调用 getDateTime() 函数?

标签: javascript reactjs


【解决方案1】:

使用setState() 函数 - 更多信息请参见this

const getDateTime = () => {
  let tempDate = new Date();
  let date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds(); 
  const currDate = "Current Date= "+date;
  this.setState({ reportStartDate: currDate})
}

【讨论】:

  • 感谢您提供资源和代码 sn-p,我让它工作了。
【解决方案2】:

如果我正确理解您的问题,您需要在最初显示输入字段时将当前日期和时间设置为输入字段,如果是这样,

首先在构造函数中使用当前日期和时间设置reportStartDate,以便在用户选择首选日期和时间之前,输入字段最初会显示当前日期

     constructor(props){
         super(props);
              this.state = {
                   reportStartDate: getDateTime()
              }
      }

现在在返回行中稍微改变一下getDateTime

      const getDateTime = () => {
          let tempDate = new Date();
          let date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds(); 
          return date;
       }

确保在用户更改日期时间时使用 setState 在更改事件处理函数中修改状态

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 2017-11-03
    • 2019-07-11
    • 1970-01-01
    • 2012-12-21
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多