ant mobile design组件库的PickerView组件不能滑动
问题
PickerView组件在开发环境可滑动,在测试环境不可滑动
-
正常开发环境是这样正常显示,并且可滑动的
-
发到测试环境后,变成了这样,并且只有中间那列可滑动,两边的都不能滑动,而且还会报警告
-
封装的组件代码如下
// 日期选择组件
const CustomDatePickerView: FC<any> = ({
customizeTab,
setCustomizeTime,
customizeTime
}) => {
const [value, setValue] = useState<number[]>(
transformDateToArray(customizeTime[customizeTab])
);
const [days, setDays] = useState<any>([]);
useEffect(() => {
// 在组件加载时设置初始值
console.log(111, customizeTime, customizeTab, value[0], value[2]);
updateDays(value[0], value[2]); // 设置天数列
// sessionStorage.setItem('isFirst', '1');
}, []);
useEffect(() => {
setValue(transformDateToArray(customizeTime[customizeTab]));
}, [customizeTab]);
const months = [
{ label: 'January', value: 0 },
{ label: 'February', value: 1 },
{ label: 'March', value: 2 },
{ label: 'April', value: 3 },
{ label: 'May', value: 4 },
{ label: 'June', value: 5 },
{ label: 'July', value: 6 },
{ label: 'August', value: 7 },
{ label: 'September', value: 8 },
{ label: 'October', value: 9 },
{ label: 'November', value: 10 },
{ label: 'December', value: 11 }
];
const years = Array.from({ length: 100 }, (_, i) => ({
label: `${dayjs().year() - 50 + i}`,
value: dayjs().year() - 50 + i
}));
const updateDays = (month, year) => {
const daysInMonth = dayjs(`${year}-${month + 1}`).daysInMonth();
const newDays = Array.from({ length: daysInMonth }, (_, i) => ({
label: `${i + 1}`,
value: i + 1
}));
setDays(newDays);
};
const onChange = debounce(val => {
const [selectedMonth, selectedDay, selectedYear] = val;
if (selectedMonth !== value[0] || selectedYear !== value[2]) {
// 动态更新天数列
updateDays(selectedMonth, selectedYear);
}
// 确保日期选项在天数列更新时不越界
const daysInSelectedMonth = dayjs(
`${selectedYear}-${selectedMonth + 1}`
).daysInMonth();
if (selectedDay > daysInSelectedMonth) {
val[1] = daysInSelectedMonth;
}
setValue(val);
customizeTime[customizeTab] = transformDate(
dayjs(`${selectedYear}-${selectedMonth + 1}-${selectedDay}`)
);
setCustomizeTime([...customizeTime]);
// }
}, 500);
return (
<PickerView
className="!bg-[#27292F]"
columns={[months, days, years]}
value={value}
onChange={onChange}
style={{ '--item-font-size': '20px' }}
/>
);
};
最终发现可能导致的原因是在本地开发环境会触发两次useEffect,所以传入的columns应该没什么问题,而测试环境是只触发一次,打断点的时候发现days这个值不对
解决办法就是 加了一个days.length 的判断就可以了,
days.length && (
<PickerView
className="!bg-[#27292F]"
columns={[months, days, years]}
value={value}
onChange={onChange}
style={{ '--item-font-size': '20px' }}
/>
)