2

我们正在从 react-day-picker 的 5.5.3 版本升级到最新版本 (7.1.10)。我查看了有关重大更改的文档并相应地修改了我们的代码。我什至将我们的代码更改为看起来像文档中的代码,但是从日历中选择日期时我无法触发 onDayChange 事件。

handleDayChange 函数永远不会触发。我不知道为什么不。我错过了什么?

import React from 'react'
import DayPickerInput from 'react-day-picker/DayPickerInput'
import './input-with-calendar.scss'

const dateFormat = 'MM/DD/YYYY'

export default class InputWithCalendar extends React.Component {
  constructor(props) {
    super(props)
    this.handleDayChange = this.handleDayChange.bind(this)
    this.state = { selectedDay: undefined }
  }

  handleDayChange(day) {
    console.log('In handleDayChange')
    this.setState({ selectedDay: day })
  }

  render() {
    const { selectedDay } = this.state
    return (
      <div className='input-with-calendar'>
        <div className='overlay-date-picker-container'>
          {selectedDay && <p>Day: {selectedDay.toLocaleDateString()}</p>}
          {!selectedDay && <p>Choose a day</p>}
          <DayPickerInput onDayChange={this.handleDayChange} />
        </div>
      </div>
    )
  }
}

这是 5.5.3 代码……这行得通

import React from 'react'
import DayPickerInput from 'react-day-picker/DayPickerInput'
import './input-with-calendar.scss'
import moment from 'moment'

const dateFormat = 'MM/DD/YYYY'

const formatDate = (date) => {
  return date && moment(date).format(dateFormat)
}

class InputWithCalendar extends React.Component {
  componentWillMount () {
    this.props.onDateChange(this.props.selectedDate)
  }

  render () {
    return (
      <div className='input-with-calendar'>
        <div className='input-with-calendar-filter-label'>Date</div>
        <div className='overlay-date-picker-container'>
          <DayPickerInput
            readOnly
            value={formatDate(this.props.selectedDate)} // value is expected to be a string
            placeholder={dateFormat}
            onDayChange={(dateAsMoment) => this.props.onDateChange(dateAsMoment && dateAsMoment.toDate())}
            dayPickerProps={{
              weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
              disabledDays: { before: new Date() }
            }}
          />
        </div>
      </div>
    )
  }
}

export default InputWithCalendar
4

1 回答 1

2

我相信你错过了value道具:

<DayPickerInput 
   value={this.state.selectedDay} 
   onDayChange={this.handleDayChange} 
/>

http://react-day-picker.js.org/examples/input-state

于 2018-08-27T08:16:18.923 回答