NextUI DateRangePicker点击分隔符/空白区域触发createTreeWalker错误求助
解决NextUI DateRangePicker点击分隔符/空白区域触发的createTreeWalker错误
问题原因
- React Hook Form的
dateRange默认值设为空字符串"",但NextUI DateRangePicker组件期望的value类型是包含start和end属性的对象(或null),类型不匹配导致DOM操作时抛出错误。 addFrond函数存在笔误:reqBody.end.year应为reqBody.dateRange.end.year。
解决步骤
- 修正默认值:将useForm的defaultValues中
dateRange改为null或{start: null, end: null} - 修复函数笔误:修正end_date拼接时的属性路径错误
- 优化Controller字段传递:明确同步DateRangePicker的value和onChange到react-hook-form
修改后的完整代码示例
import { DateRangePicker } from "@nextui-org/react"; import { useForm, Controller } from "react-hook-form"; import axios from "axios"; import Image from "next/image"; const YourComponent = () => { const token = "your-token-here"; const calendar = "/path/to/calendar-icon.png"; const { control, handleSubmit, setValue, getValues, formState: { errors }, } = useForm({ defaultValues: { title: "", dateRange: null, // 替换原空字符串为null category: "", location: "", budget: "", currency: "", importance: "", tags: [], desc: "", }, }); async function addFrond(reqBody) { if (!reqBody.dateRange?.start || !reqBody.dateRange?.end) return; const start_date = `${reqBody.dateRange.start.day}/${reqBody.dateRange.start.month}/${reqBody.dateRange.start.year}`; // 修复笔误:reqBody.end.year → reqBody.dateRange.end.year const end_date = `${reqBody.dateRange.end.day}/${reqBody.dateRange.end.month}/${reqBody.dateRange.end.year}`; try { const { data } = await axios.post( "your-api-endpoint", { title: reqBody.title, start_date, end_date, category: reqBody.category, }, { headers: { Accept: "application/json", Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, } ); console.log(data); } catch (error) { console.log(error); } } return ( <form onSubmit={handleSubmit(addFrond)}> <Controller name="dateRange" control={control} rules={{ required: "Date range is required", }} render={({ field }) => ( <DateRangePicker value={field.value} onChange={(value) => field.onChange(value)} label="Start Date - End Date" variant="bordered" labelPlacement="outside" visibleMonths={2} selectorIcon={ <Image src={calendar} className="w-[18px] h-[18px]" alt="calendar icon" /> } isInvalid={!!errors.dateRange?.message} errorMessage={errors.dateRange?.message} classNames={{ base: "mt-0 h-[68px]", label: "text-textColor font-normal text-sm", inputWrapper: "border-[0.86px] p-0 border-solid border-[#E5E4EB] rounded-[8px] min-h-[42px] flex-row-reverse", innerWrapper: "px-[18px]", segment: "uppercase date-picker-frond text-sm font-normal", selectorButton: "order-first min-w-[18px] max-h-[18px] h-[18px] me-1", separator: "mx-0 date-picker-frond text-sm font-normal", }} /> )} /> {/* 其他表单元素 */} <button type="submit">Submit</button> </form> ); }; export default YourComponent;
额外说明
- 建议升级
@nextui-org/react到最新版本,旧版本可能存在类似DOM操作的已知bug。 - 手动传递
value和onChange比直接展开{...field}更稳妥,可避免react-hook-form字段与组件属性的冲突。
内容的提问来源于stack exchange,提问作者Mazen Ahmed
相关产品推荐
相关产品推荐

