简体   繁体   English

如何将带有单个输入的日期范围添加到 react-datepicker

[英]How can I add a date range with a single input to react-datepicker

I want to create a date range component that will fit both start and end dates into a single input.我想创建一个日期范围组件,它将开始日期和结束日期都放入一个输入中。 I tried using the example here https://reactdatepicker.com/#example-date-range-for-one-datepicker but it doesnt seem to display the endDate.我尝试在这里使用示例https://reactdatepicker.com/#example-date-range-for-one-datepicker但它似乎没有显示 endDate。 I've set up a custom input to display both values, but I don't know how to update them both with a single onChange prop in my datePicker.我已经设置了一个自定义输入来显示这两个值,但我不知道如何在我的 datePicker 中使用单个 onChange 道具更新它们。 I believe this has caused the component to fail with a RangeError: invalid time value.我相信这导致组件失败并出现 RangeError: invalid time value。

const CustomDatePicker = (props) => {
  const {
    className,
    startDateId,
    endDateId,
    startLabel,
    endLabel,
    displayFormat,
    onStartDateChange,
    onEndDateChange,
    locale,
    startDate,
    endDate,
  } = props

const CustomInput = ({ value, onClick}) => {
    return 
     
        <input
          className="my-input"
          type="text"
          onClick={onClick}
          value={`${startDate} - ${endDate}`}
        />
      </div>
   
    )

return <DatePicker
            id={startDateId}
            selected={startDate}
            selectsRange
            startDate={startDate}
            endDate={endDate}
            placeholderText={placeholder}
            dateFormat={displayFormat}
            onChange={onStartDateChange}
            locale={selectLocale(locale)}
            customInput={<CustomInput />}
          />
}

If you follow the website you linked to, you can see that just when the input changes, it changes both the startDate as the endDate.如果您关注您链接到的网站,您可以看到就在输入更改时,它会将 startDate 更改为 endDate。 This way you can keep both of them updated.这样您就可以使它们都保持更新。 So this would look like:所以这看起来像:

JSX: JSX:

          <DatePicker
            id={startDateId}
            selected={startDate}
            selectsRange
            startDate={startDate}
            endDate={endDate}
            placeholderText={placeholder}
            dateFormat={displayFormat}
            onChange={onChange}
            locale={selectLocale(locale)}
            customInput={<CustomInput />}
          />
         
         <input value={`${startDate} - ${endDate}`} />

Function: Function:

const onChange = dates => {
    const [start, end] = dates;
    setStartDate(start);
    setEndDate(end);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM