【问题标题】:react-datepicker time selection with secondsreact-datepicker 以秒为单位的时间选择
【发布时间】:2020-08-03 08:59:54
【问题描述】:

我还需要从 react date picker 中选择秒。我已经阅读了找到这个的文档

在这个解决方案中,我可以从中选择小时、分钟、上午/下午,但没有秒选项是否有任何方法可以自定义以从这里选择秒。需要帮助,下面的示例 (look for input Time)

我尝试过更改日期格式

dateFormat="MM/dd/yyyy h:mm:ss aa" 不工作

() => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      timeInputLabel="Time:"
      dateFormat="MM/dd/yyyy h:mm aa"
      showTimeInput
    />
  );
};

我找到了显示秒数的方法,但这工作正常,但在我们选择时间后整个对话框关闭后在模型中。我在 MaterialUi 对话框中使用它

() => {
  const [startDate, setStartDate] = useState(new Date());
  const ExampleCustomTimeInput = ({ value, onChange }) => (
    <input
      type="time"
      step="1"
      value={value}
      onChange={e => onChange(e.target.value)}
      style={{ border: "solid 1px pink" }}
    />
  );
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      showTimeInput
      customTimeInput={<ExampleCustomTimeInput />}
    />
  );
};

【问题讨论】:

  • 谢谢!我正在寻找相同的

标签: javascript material-ui react-datepicker


【解决方案1】:

您可以在其中使用customTimeInput 属性和路径自己的onChange 函数:

customTimeInput={
        <CustomTimeInput
          onChangeCustom={this.handleChangeTime}
        />
      }

这是组件:

const CustomTimeInput = ({ date, onChangeCustom}) => {
  const value = date instanceof Date && !isNaN(date)
  ? // Getting time from Date beacuse `value` comes here without seconds
    date.toLocaleTimeString('it-IT')
  : '';

  return (
    <input
      className="bp3-input bp3-fill"
      type="time"
      step="1"
      value={value}
      onChange={(event) => onChangeCustom(date, event.target.value)}
    />);
};

以及回调示例:

handleChangeTime = (date, time) => {
  const [hh, mm, ss] = time.split(':');
  const targetDate = date instanceof Date && !isNaN(date) ? date : new Date();
  targetDate.setHours(Number(hh) || 0, Number(mm) || 0, Number(ss) || 0);
  this.handleDateChange(targetDate);
};

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    相关资源
    最近更新 更多