【问题标题】:react-bootstrap-daterangepicker initial statereact-bootstrap-daterangepicker 初始状态
【发布时间】:2021-03-21 08:38:57
【问题描述】:

react-bootstrap-daterangepicker 的初始状态未在我的项目中更新。

import DateRangePicker from 'react-bootstrap-daterangepicker';
...

constructor(props) {
    super(props);
    this.state = {
        startDate: new Date(),
        endDate: new Date()
    };
}

...

updateDates = (event) => {
    const period = event.target.value;
    let start, end = null;
    const today = new Date();
    switch(period) {
        case 'today':
            start = today;
            end = today;
            break;
        case 'thisMonth':
            start = new Date(today.getFullYear(), today.getMonth(), 1);
            end = new Date(today.getFullYear(), today.getMonth()+1, 0);
            break;
        case 'thisWeek':
            const first = today.getDate() - today.getDay();
            const last = first + 6;
            start = new Date(today.setDate(first));
            end = new Date(today.setDate(last));
            break;
        case 'thisYear':
            start = new Date(today.getFullYear(), 0, 1);
            end = new Date(today.getFullYear(), 11, 31);
            break;
        default:
            break;
    }
    
    if(start && end) {
        this.setState({
            startDate: start,
            endDate: end
        });
    }
}

...

render() {
   const sDate = this.state.startDate.toLocaleDateString();
   const eDate = this.state.endDate.toLocaleDateString();
   console.log(sDate);
   console.log(eDate);

   ...

   <DateRangePicker
    initialSettings={{ startDate: sDate.toString(), endDate: eDate.toString() }}
    onCallback={this.handleSelect}
>
    <input type="text" className="form-control" />
   </DateRangePicker>
   
   ...

   <select className="form-control" id="dtOption" onChange={this.updateDates}>
    <option value="">Select</option>
    <option value="today">Today</option>
    <option value="thisMonth">This Month</option>
    <option value="thisWeek">This Week</option>
    <option value="thisYear">This Year</option>
   </select>
}

这很奇怪,因为 render() 方法中的 console.logs 在我在下拉列表中选择日期范围后会显示更新的日期,但它不会更新 DateRangePicker 输入。

【问题讨论】:

  • 我猜到的一个原因是 date.toLocaleDateString() 没有以 DateRangePicker 组件的预期格式返回日期。值得尝试。祝你好运
  • @SachinVishwakarma 它是。 DateRangePicker,格式为 mm/dd/yyyy 的字符串除外

标签: reactjs react-bootstrap


【解决方案1】:

您需要使用 refs 从组件外部更新日期范围。您也可以使用 key prop 并在每次需要更新范围时提供唯一值。这在此处的文档中得到了很好的解释。 https://projects.skratchdot.com/react-bootstrap-daterangepicker/?path=/story/daterangepicker--change-initialsettings-range-data

【讨论】:

    猜你喜欢
    • 2019-01-04
    • 2017-01-25
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2018-08-22
    • 2021-07-09
    • 2019-05-08
    • 2021-09-11
    相关资源
    最近更新 更多