add: support value prop to control the selected date

This commit is contained in:
Astrian Zheng 2025-02-19 16:35:22 +11:00
parent d8658de5ca
commit f55c72b535
Signed by: Astrian
SSH Key Fingerprint: SHA256:rVnhx3DAKjujCwWE13aDl7uV6+9U1MvydLkNRXJrBiA
2 changed files with 31 additions and 2 deletions

View File

@ -3,9 +3,15 @@ import { WeekPicker } from "../src/index.ts"
import './app.scss' import './app.scss'
export default () => { export default () => {
return (<div className='app'> return (<div className='app'>
<div className="border"> <div className="border">
<WeekPicker /> <WeekPicker value={{
year: 2025,
month: 1,
day: 1
}} />
</div> </div>
</div>) </div>)
} }

View File

@ -3,7 +3,21 @@ import RightArrowIcon from '@/assets/icons/right-arrow.svg'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { getCalendarDates, getL10Weekday } from '../utils' import { getCalendarDates, getL10Weekday } from '../utils'
export default () => { interface Props {
value?: Date | { year: number, month: number, day: number }
}
/**
* A panel that allows users to select a date.
*
* @component
*
* @param {Object} props
* @param {Date | { year: number, month: number, day: number }} props.value - Control the selected
* date programmatically, including situations like provide a default value or control the selected
* date by parent component.
*/
export default ({ value }: Props) => {
const [currentMonth, setCurrentMonth] = useState(new Date().getMonth()) const [currentMonth, setCurrentMonth] = useState(new Date().getMonth())
const [currentYear, setCurrentYear] = useState(new Date().getFullYear()) const [currentYear, setCurrentYear] = useState(new Date().getFullYear())
const [selectedDate, setSelectedDate] = useState(new Date()) const [selectedDate, setSelectedDate] = useState(new Date())
@ -15,6 +29,15 @@ export default () => {
setDates(getCalendarDates(currentMonth, currentYear)) setDates(getCalendarDates(currentMonth, currentYear))
}, [currentMonth, currentYear]) }, [currentMonth, currentYear])
useEffect(() => {
if (!value) return
const date = value instanceof Date ? value : new Date(value.year, value.month - 1, value.day)
console.log(date)
setSelectedDate(date)
setCurrentMonth(date.getMonth())
setCurrentYear(date.getFullYear())
}, [value])
function selectDate(date: Date) { function selectDate(date: Date) {
setSelectedDate(date) setSelectedDate(date)
} }