【问题标题】:How to get the value of the date input in ReactJS?如何在 ReactJS 中获取日期输入的值?
【发布时间】:2019-01-18 21:31:11
【问题描述】:

我有一个输入日期的注册表单。

我的日期输入代码是:

birthDate: new Date(),

this.handleSubmit = this.handleSubmit.bind(this);
this.handledChange = this.handledChange.bind(this);


handledChange(date) {
  this.setState({
    birthDate: date
  });
}

<ControlLabel>Date de naissance</ControlLabel>
  <FormGroup controlId="birthDate" bsSize="large">
    <FormControl
      autoFocus
      type="date"
      value={this.state.birthDate}
      onChange={this.handledChange}
    />
  </FormGroup>

我提交的时候,控制台输入的日期是undefined

我想要它的格式:YYYY-MM-DD

请问我该如何解决?

【问题讨论】:

    标签: javascript reactjs input datepicker date-format


    【解决方案1】:

    你不会直接得到选定的日期,它应该是通过事件目标

    改变

    handledChange(date) {
        this.setState({
          birthDate: date
        });
      }
    

    handledChange(event) {
        this.setState({
          birthDate: event.target.value
        });
      }
    

    【讨论】:

    • 还是同一个问题,是undefined
    【解决方案2】:

    您还可以在提交后使用表单的 ID 提取表单的输入值。
    您可以尝试在您的提交方法中使用这样的:

    让 selectedDate = document.getElementById('birthDate')

    这里的BirthDate是指FormGroup的controlId

    【讨论】:

    • 同样的问题
    • 只是一个我能想到的小问题。您是否确定在提交时是否调用了您的提交处理程序?
    【解决方案3】:

    这就像一个宝石。如果您仍然遇到问题,请尝试一下

                 <input
                    type="date"
                    name="expiration date"
                    value={this.state.expiration_date}
                    onChange={event => this.setState({expiration_date: event.target.value})} 
                  />
    
    onChange = (key, value) => {
        this.setState({
          [key]: value
        })
      }
    

    【讨论】:

    • 与公认的答案相比,这有什么优势?在使用已接受的答案添加旧问题的答案时,指出您的答案所针对的问题的新方面非常重要。通过添加一些关于它们的工作原理和工作原理的解释,几乎总是可以改进纯代码的答案。
    猜你喜欢
    • 2021-01-06
    • 2020-04-21
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    相关资源
    最近更新 更多