是的,你可以。您可以标记任意数量的日期。解决方案取决于如何您要标记它们。
如果您只想在日历中的日期上标记它们,可以使用<StaticDatePicker> renderDay 属性。如果您想在其他地方标记它们(例如工具栏或页脚),则必须提供自定义工具栏标题或设计自己的自定义工具栏或页脚。
本文的其余部分假设您只想在日历中标记日期。
根据documentation,renderDay 属性是一个具有以下签名的函数:
day:渲染的日期。
selectedDays:当前选择的日期。
pickersDayProps:属性渲染日期。
return (JSX.Element): 代表一天的元素。
请注意,标记三个日期与日期选择器的 值 具有三个日期不同。日期选择器是一个让用户可以轻松输入单个日期的组件。您可以随意管理该用户输入。您可能希望使用 React.useState() 来管理包含三个日期值的数组。或者您可能希望使用 Redux。无论您选择什么,您都必须管理这三个日期。 StaticDatePicker 不会为您执行此操作。 StaticDatePicker 可以根据您将样式应用于日历中的日期的方式来显示您选择的数据。您可以使用 <PickersDay> 组件的属性将样式应用于日期。
<PickersDay> 组件(或包装它的更高阶组件)从 renderDay 函数返回。根据要呈现的日期是否与您的三个日期之一匹配,您可以将 DOM 元素 id 或类名应用于 <PickersDay> 组件的根。然后,您的 CSS 将应用所需的样式。如果您想应用 Material-UI 使用的样式来指示选定日期,只需使用 Material-UI 为其 StaticDatePicker 使用的全局类名称。
不幸的是,<DatePicker> 组件的最新版本 (@mui/x-date-pickers) 的 API documentation 没有记录全局类名称。但是,您可以使用 Firefox 开发者工具的 Inspector 选项卡找到它们。用于设置选定日期样式的类是 .Mui-selected。
示例代码如下所示:
// Using React.useState(), 'dateArray' is the state variable used to store the
// dates you consider to be selected. 'dateArray' should be updated using the
// 'setDateArray()' function based on code you provide to validate the dates
// chosen by the user. See https://reactjs.org/docs/hooks-state.html for more
// on using React.useState().
// 'initial_values' could be empty, could come from a database, etc.
const [ dateArray, setDateArray ] = React.useState( [ initial_values ] );
...
<StyledContainer>
<div className="reminders_title">Reminders</div>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<StaticDatePicker
orientation="landscape"
openTo="day"
value={value}
onChange={(newValue) => {
setValue(newValue)
}}
renderInput={(params) => <TextField {...params} />}
renderDay={(day, selectedDays, pickersDayProps) => {
let selectedMuiClass = '';
// Pseudo-code here! You will have to use the proper functions from the
// date-fns library to evaluate if 'day' is in your dateArray.
if ( dateArray.includes( day ) ) {
selectedMuiClass = 'Mui-selected';
}
return (
<PickersDay
className={ selectedMuiClass }
{ ...pickersDayProps }
/>
);
}}
/>
</LocalizationProvider>
</StyledContainer>
...