如何为type="time"的Input组件设置默认值?
解决time类型输入框默认时间不显示的问题
问题出在你用的时间格式不符合HTML time输入框的要求:
- HTML的
time类型输入框只接受HH:mm或HH:mm:ss格式的字符串(24小时制,数字需补零到两位) new Date().toLocaleTimeString()返回的是本地化格式(比如"下午2:30"或"2:30 PM"这类非标准格式),这种格式不被time输入框识别,所以不会显示内容。
解决方案一:手动格式化当前时间
写个工具函数生成符合要求的时间字符串:
const getValidTimeFormat = () => { const now = new Date(); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); // 按需返回HH:mm或HH:mm:ss格式 return `${hours}:${minutes}:${seconds}`; }; // 在组件中使用 <Input value={getValidTimeFormat()} type="time" id="time" {...form.register("time")} />
解决方案二:用Intl.DateTimeFormat生成标准格式
通过国际化API直接生成24小时制的标准时间字符串:
const formattedTime = new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' }).format(new Date()); <Input value={formattedTime} type="time" id="time" {...form.register("time")} />
结合React Hook Form的最佳写法
更推荐在useForm的defaultValues里设置默认值,不用手动给Input传value:
const form = useForm({ defaultValues: { time: getValidTimeFormat() } }); // 组件中直接使用register <Input type="time" id="time" {...form.register("time")} />
内容的提问来源于stack exchange,提问作者Mathew
相关产品推荐
相关产品推荐

