行为
选择后关闭
当启用 shouldCloseOnSelect 时,选择器在选定结束日期后会自动确认并关闭。
import { useState } from "react";import { DateRangePicker } from "react-date-range-picker-tailwind4";
function ShouldCloseOnSelect() { const [value, setValue] = useState<{ start: Date | null; end: Date | null }>({ start: null, end: null, });
return <DateRangePicker value={value} onChange={setValue} shouldCloseOnSelect />;}多个月份
并排显示多于默认的两个月份。
import { useState } from "react";import { DateRangePicker } from "react-date-range-picker-tailwind4";
function MultiMonth() { const [value, setValue] = useState<{ start: Date | null; end: Date | null }>({ start: null, end: null, });
return <DateRangePicker value={value} onChange={setValue} numberOfMonths={3} />;}表单集成
使用 name 属性来包含用于原生表单提交的隐藏输入。
💡 Tip
此示例中的提交按钮样式是自定义的 — 本库仅提供日期选择器。
import { type SubmitEvent, useState } from "react";import { DateRangePicker } from "react-date-range-picker-tailwind4";
function FormIntegration() { const [value, setValue] = useState<{ start: Date | null; end: Date | null }>({ start: null, end: null, });
const handleSubmit = (e: SubmitEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.currentTarget); const start = formData.get("booking"); const end = formData.get("booking-end"); alert( `Submitted range: ${typeof start === "string" ? start : ""} ~ ${typeof end === "string" ? end : ""}`, ); };
return ( <form onSubmit={handleSubmit} style={{ display: "flex", alignItems: "center", gap: 8 }}> <DateRangePicker value={value} onChange={setValue} name="booking" /> <button type="submit" style={{ padding: "6px 14px", border: "1px solid #d1d5db", borderRadius: 6, background: "#3b82f6", color: "#fff", cursor: "pointer", fontSize: 13, }} > Submit </button> </form> );}