如何在imask库中避免删除起始日期末位后被结束日期字符替换?
解决日期范围掩码删除字符时的占位符填充问题
可以通过在IMask配置中添加overwrite: false,并确保各日期块的placeholderChar配置正确,实现删除起始日期最后一个字符时用指定占位符填充,而非被结束日期的数字替换。
修改后的代码
import { IMask, useIMask } from "react-imask"; export default function App() { const { ref } = useIMask<HTMLInputElement>({ mask: "from - to", pattern: "d`.m`.0000 - d`.m`.0000", blocks: { from: { mask: Date, blocks: { d: { mask: IMask.MaskedRange, placeholderChar: "д", from: 1, to: 31, maxLength: 2, }, m: { mask: IMask.MaskedRange, placeholderChar: "м", from: 1, to: 12, maxLength: 2, }, Y: { mask: IMask.MaskedRange, placeholderChar: "г", from: 1900, to: 2999, maxLength: 4, }, }, }, to: { mask: Date, blocks: { d: { mask: IMask.MaskedRange, placeholderChar: "д", from: 1, to: 31, maxLength: 2, }, m: { mask: IMask.MaskedRange, placeholderChar: "м", from: 1, to: 12, maxLength: 2, }, Y: { mask: IMask.MaskedRange, placeholderChar: "г", from: 1900, to: 2999, maxLength: 4, }, }, }, }, lazy: true, placeholderChar: " ", overwrite: false, // 关键配置:关闭覆盖模式,删除后用占位符填充空缺位置 }); return ( <div className="App"> <input ref={ref} style={{ width: 180 }} /> </div> ); }
原理说明
overwrite: false:禁用IMask默认的「删除字符后用后续内容补位」行为,改为删除后用对应块的placeholderChar填充空缺位置。- 各日期块独立配置
placeholderChar:确保删除起始日期的字符时,空缺处显示对应的д/м/г占位符,而非结束日期的内容。
内容的提问来源于stack exchange,提问作者Сергей Анохин
相关产品推荐
相关产品推荐

