index.tsx 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import React, { Component, GetDerivedStateFromProps, createRef, RefObject } from 'react'
  2. import $ from 'jquery'
  3. import moment from 'moment'
  4. import classnames from 'classnames'
  5. import 'bootstrap-datepicker'
  6. import { Icon } from 'antd'
  7. import styles from './MultiDatePicker.less'
  8. interface IMultiDatePickerProps {
  9. value: string
  10. format: string
  11. size?: 'default' | 'large' | 'small'
  12. placeholder: string
  13. onChange: (value: string) => any
  14. }
  15. interface IMultiDatePickerStates {
  16. value: string
  17. }
  18. class MultiDatePicker extends Component<IMultiDatePickerProps, IMultiDatePickerStates> {
  19. public state: IMultiDatePickerStates = {
  20. value: this.props.value || ''
  21. }
  22. public static defaultProps: Partial<IMultiDatePickerProps> = {
  23. format: 'YYYY-MM-DD'
  24. }
  25. private input: RefObject<HTMLInputElement> = createRef()
  26. constructor (props) {
  27. super(props)
  28. $.fn.datepicker.dates['zh'] = {
  29. days: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  30. daysShort: ['日', '一', '二', '三', '四', '五', '六'],
  31. daysMin: ['日', '一', '二', '三', '四', '五', '六'],
  32. months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  33. monthsShort: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  34. today: '今天',
  35. clear: '清除',
  36. format: this.props.format.toLowerCase(),
  37. titleFormat: 'yyyy MM', /* Leverages same syntax as 'format' */
  38. weekStart: 0
  39. }
  40. }
  41. public componentDidMount () {
  42. $(this.input.current)
  43. .datepicker({
  44. multidate: true,
  45. clearBtn: true,
  46. language: 'zh'
  47. })
  48. .on('changeDate', (e) => {
  49. const val = e.dates.map((d) => moment(d).format(this.props.format)).join(',')
  50. this.props.onChange(val)
  51. })
  52. }
  53. public static getDerivedStateFromProps: GetDerivedStateFromProps<
  54. IMultiDatePickerProps,
  55. IMultiDatePickerStates
  56. > = (props) => {
  57. return {
  58. value: props.value
  59. }
  60. }
  61. public render () {
  62. const { size } = this.props
  63. const inputClassNames = classnames({
  64. 'ant-input': true,
  65. 'ant-input-lg': size === 'large',
  66. 'ant-input-sm': size === 'small'
  67. })
  68. return (
  69. <span className={styles.datepicker}>
  70. <input
  71. type="text"
  72. placeholder={this.props.placeholder || '请选择日期(多选)'}
  73. className={inputClassNames}
  74. value={this.state.value}
  75. ref={this.input}
  76. readOnly
  77. />
  78. <Icon type="calendar" />
  79. </span>
  80. )
  81. }
  82. }
  83. export default MultiDatePicker