React DayPicker Input自定义captionElement下拉onChange不触发如何解决
问题修复方案
核心问题点
react-select的onChange回调参数为选中的选项对象,而非原生事件对象,原有逻辑中对e.target.form的调用不符合组件接口规范,导致回调逻辑无法正常执行。Select组件未绑定value属性,选中状态无法同步到组件视图,出现选中后无回显的问题。- 自定义的
YearMonthForm、YearMonthFormInput组件定义在父组件函数体内,父组件每次重渲染都会生成新的组件引用,导致原有组件实例被销毁,事件绑定失效。 dayPickerProps中设置了canChangeMonth: false,会全局禁用月份切换能力,影响自定义标题栏的切换逻辑。
修复后代码
import { useState } from 'react'; import DayPickerInput from 'react-day-picker/DayPickerInput'; import Select from 'react-select'; import type { CaptionElementProps } from 'react-day-picker'; // 组件移到父组件外部,避免重渲染时重复创建 const YearMonthForm = ({ date, localeUtils, onMonthChange }: any) => { const currentYear = new Date().getFullYear(); const fromMonth = new Date(currentYear, 0); const toMonth = new Date(currentYear + 10, 11); const months = localeUtils.getMonths(); const years = []; for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) { years.push(i); } // 适配react-select的回调参数格式 const handleMonthChange = (selectedOption: any) => { console.log('The handlechange has been triggered'); const newMonth = new Date(date.getFullYear(), months.indexOf(selectedOption.value)); onMonthChange(newMonth); }; const style = { control: (base: any, state: any) => ({ ...base, border: state.isFocused ? 0 : 0, boxShadow: state.isFocused ? 0 : 0, '&:hover': { border: !state.isFocused ? '1px solid red' : '1px solid blue', }, }), }; // 绑定选中值实现回显 const selectedMonth = months[date.getMonth()]; const monthOptions = months.map(m => ({ value: m, label: m })); return ( <form className="DayPicker-Caption"> <div style={{ width: '150px' }}> <Select name="month" id="month" value={monthOptions.find(opt => opt.value === selectedMonth)} onChange={handleMonthChange} options={monthOptions} styles={style} /> </div> </form> ); }; const YearMonthFormInput = (props1: React.PropsWithChildren<CaptionElementProps>) => { return <YearMonthForm date={props1.date} localeUtils={props1.localeUtils} onMonthChange={props1.onMonthChange} />; }; const MyComponent = () => { const [month, setMonth] = useState<Date>(new Date(2018, 10)); return ( <DayPickerInput dayPickerProps={{ canChangeMonth: true, // 开启月份切换权限 captionElement: YearMonthFormInput, month, onMonthChange: setMonth // 绑定官方内置的月份切换回调 }} /> ); }; export default MyComponent;
额外优化说明
- 直接使用DayPicker内置的
onMonthChange回调处理月份更新,无需维护冗余状态 - 月份选项直接从
localeUtils.getMonths()生成,不需要手动写死,天然适配多语言场景 - 所有自定义组件移到父组件外部,避免不必要的组件销毁重建,提升性能
内容的提问来源于stack exchange,提问作者juztcode
相关产品推荐
相关产品推荐

