在MUI StaticDatePicker日历中突出显示日期。

huangapple go评论75阅读模式
英文:

Highlight the days in MUI StaticDatePicker Calender

问题

我正在尝试将MUI StaticDatePicker添加到我的React网站中。我想要的是在日历中使用蓝色圆圈或徽章来突出显示几天。我尝试了各种方法来实现这一点,但无法在日历中获取突出显示的日期输出。如果有人知道如何做到这一点,请帮助我。在下面的代码中,我试图突出显示日历中的highlightDays状态值。

我使用了dayjs库来处理我的网站中的时间和日期相关数据。但出于某种原因,我无法看到我的renderDay正在运行。最后,我想要实现的是阻止今天之前的日期(即当前日期之前的日期)并在日历中突出显示即将发生的事件日期。

import { React, useState } from "react";
import dayjs from "dayjs";
import { Box, TextField } from "@mui/material";
import { Loading } from "../pages/index.mjs";
import { EventCard } from "./index.mjs";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { StaticDatePicker } from "@mui/x-date-pickers/StaticDatePicker";
import { useReadAllEvent } from "../hooks/useEvent.mjs";
import { PickersDay } from "@mui/x-date-pickers";
import { Badge } from "@mui/material";

const SessionBooking = ({ doctor }) => {
  const [value, setValue] = useState("");

  const [highlightDays, setHighlightDays] = useState([
    "2023-06-01",
    "2023-06-02",
    "2023-06-04",
  ]);

  console.log(value);

  const { data: eventSet, isLoading } = useReadAllEvent({
    onSuccess: (message) => {},
    onError: (message) => {},
    session: { id: doctor, today: dayjs().format("YYYY-MM-DD") },
  });

  if (isLoading) return <Loading />;

  console.log(eventSet);

  const events = eventSet.map(
    ({ key, countPatient, start, end, maxPatients }) => (
      <EventCard
        key={key}
        started={start}
        ended={end}
        patients={countPatient}
        max={maxPatients}
      />
    )
  );

  return (
    <Box
      mt={2}
      sx={{
        display: "grid",
        gridTemplateColumns: {
          xs: "repeat(1, 1fr)",
          sm: "repeat(1, 1fr)",
          md: "repeat(2, 1fr)",
        },
        gap: 1,
      }}
    >
      <Box>
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <StaticDatePicker
            orientation="portrait"
            openTo="day"
            value={value}
            onChange={(newValue) => {
              setValue(newValue);
            }}
            renderInput={(params) => <TextField {...params} />}
            renderDay={(day, _value, DayComponentProps) => {
              const isSelected =
                !DayComponentProps.outsideCurrentMonth &&
                highlightDays.includes(dayjs(day).format("YYYY-MM-DD"));

              return (
                <Badge
                  key={day.toString()}
                  overlap="circular"
                  badgeContent={isSelected ? "-" : undefined}
                  color="primary"
                >
                  <PickersDay {...DayComponentProps} />
                </Badge>
              );
            }}
          />
        </LocalizationProvider>
      </Box>

      <Box>{events}</Box>
    </Box>
  );
};

export default SessionBooking;
英文:

I'm trying implement MUI StaticDatePicker to my react website. What I want is to highlight several days in the calendar using blue circle or a badge. I tried various methods achieve this but I couldn't get the highlighted dates output in the calendar. If anyone knows how to do this pls help me. In the below code I'm trying to highlight the highlightDays state values in calendar.

I used dayjs library handle time and date realated data in my website. But whatever reason I couldn't see my renderDay is running. Finally what I want to achieve is block the date prior to the today which is dates before the current dates and highlight the upcoming event dates in the calendar.

import { React, useState } from &quot;react&quot;;
import dayjs from &quot;dayjs&quot;;
import { Box, TextField } from &quot;@mui/material&quot;;
import { Loading } from &quot;../pages/index.mjs&quot;;
import { EventCard } from &quot;./index.mjs&quot;;
import { AdapterDayjs } from &quot;@mui/x-date-pickers/AdapterDayjs&quot;;
import { LocalizationProvider } from &quot;@mui/x-date-pickers/LocalizationProvider&quot;;
import { StaticDatePicker } from &quot;@mui/x-date-pickers/StaticDatePicker&quot;;
import { useReadAllEvent } from &quot;../hooks/useEvent.mjs&quot;;
import { PickersDay } from &quot;@mui/x-date-pickers&quot;;
import { Badge } from &quot;@mui/material&quot;;
const SessionBooking = ({ doctor }) =&gt; {
const [value, setValue] = useState(&quot;&quot;);
const [highlightDays, setHighlightDays] = useState([
&quot;2023-06-01&quot;,
&quot;2023-06-02&quot;,
&quot;2023-06-04&quot;,
]);
console.log(value);
const { data: eventSet, isLoading } = useReadAllEvent({
onSuccess: (message) =&gt; {},
onError: (message) =&gt; {},
session: { id: doctor, today: dayjs().format(&quot;YYYY-MM-DD&quot;) },
});
if (isLoading) return &lt;Loading /&gt;;
console.log(eventSet);
const events = eventSet.map(
({ key, countPatient, start, end, maxPatients }) =&gt; (
&lt;EventCard
key={key}
started={start}
ended={end}
patients={countPatient}
max={maxPatients}
/&gt;
)
);
return (
&lt;Box
mt={2}
sx={{
display: &quot;grid&quot;,
gridTemplateColumns: {
xs: &quot;repeat(1, 1fr)&quot;,
sm: &quot;repeat(1, 1fr)&quot;,
md: &quot;repeat(2, 1fr)&quot;,
},
gap: 1,
}}
&gt;
&lt;Box&gt;
&lt;LocalizationProvider dateAdapter={AdapterDayjs}&gt;
&lt;StaticDatePicker
orientation=&quot;portrait&quot;
openTo=&quot;day&quot;
value={value}
onChange={(newValue) =&gt; {
setValue(newValue);
}}
renderInput={(params) =&gt; &lt;TextField {...params} /&gt;}
renderDay={(day, _value, DayComponentProps) =&gt; {
const isSelected =
!DayComponentProps.outsideCurrentMonth &amp;&amp;
highlightDays.includes(dayjs(day).format(&quot;YYYY-MM-DD&quot;));
return (
&lt;Badge
key={day.toString()}
overlap=&quot;circular&quot;
badgeContent={isSelected ? &quot;-&quot; : undefined}
color=&quot;primary&quot;
&gt;
&lt;PickersDay {...DayComponentProps} /&gt;
&lt;/Badge&gt;
);
}}
/&gt;
&lt;/LocalizationProvider&gt;
&lt;/Box&gt;
&lt;Box&gt;{events}&lt;/Box&gt;
&lt;/Box&gt;
);
};
export default SessionBooking;

答案1

得分: 1

像Steve说的那样,&lt;StaticDatePicker /&gt;在更新的版本中不再接受renderDay属性。而是必须使用插槽。StaticDatePicker的代码如下:

import React, { useState } from "react";
import dayjs from "dayjs";
import { useReadAllEvent } from "../hooks/useEvent.mjs";
import { Box } from "@mui/material";
import { styled } from "@mui/material/styles";
import { Loading } from "../pages/index.mjs";
import { EventCard } from "./index.mjs";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { PickersDay } from "@mui/x-date-pickers/PickersDay";
import { StaticDatePicker } from "@mui/x-date-pickers/StaticDatePicker";

const HighlightedDay = styled(PickersDay)(({ theme }) => ({
  "&.Mui-selected": {
    backgroundColor: theme.palette.primary.main,
    color: theme.palette.primary.contrastText,
  },
}));

// 高亮显示highlightedDays数组中的日期
const ServerDay = (props) => {
  const { highlightedDays = [], day, outsideCurrentMonth, ...other } = props;

  const isSelected =
    !props.outsideCurrentMonth &&
    highlightedDays.includes(day.format("YYYY-MM-DD"));

  return (
    <HighlightedDay
      {...other}
      outsideCurrentMonth={outsideCurrentMonth}
      day={day}
      selected={isSelected}
    />
  );
};

const SessionBooking = ({ doctor }) => {
  const [value, setValue] = useState("");
  const [highlightedDays, setHighlitedDays] = useState([
    "2023-07-01",
    "2023-07-09",
    "2023-07-21",
    "2024-07-12",
  ]);

  const today = dayjs();

  return (
    <Box>
      <LocalizationProvider dateAdapter={AdapterDayjs}>
        <StaticDatePicker
          defaultValue={today}
          minDate={today}
          maxDate={today.add(1, "month")}
          slots={{
            day: ServerDay,
          }}
          slotProps={{
            day: {
              highlightedDays,
            },
          }}
        />
      </LocalizationProvider>
    </Box>
  );
};

export default SessionBooking;

这是StaticDatePicker的更新后代码。如果需要进一步的帮助,请告诉我。

英文:

Like steve said &lt;StaticDatePicker /&gt; doesn't accept renderDay prop in newer version. Instead have to use slots. Code for StaticDatePicker

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import React, { useState } from &quot;react&quot;;
import dayjs from &quot;dayjs&quot;;
import { useReadAllEvent } from &quot;../hooks/useEvent.mjs&quot;;
import { Box } from &quot;@mui/material&quot;;
import { styled } from &quot;@mui/material/styles&quot;;
import { Loading } from &quot;../pages/index.mjs&quot;;
import { EventCard } from &quot;./index.mjs&quot;;
import { AdapterDayjs } from &quot;@mui/x-date-pickers/AdapterDayjs&quot;;
import { LocalizationProvider } from &quot;@mui/x-date-pickers/LocalizationProvider&quot;;
import { PickersDay } from &quot;@mui/x-date-pickers/PickersDay&quot;;
import { StaticDatePicker } from &quot;@mui/x-date-pickers/StaticDatePicker&quot;;
const HighlightedDay = styled(PickersDay)(({ theme }) =&gt; ({
&quot;&amp;.Mui-selected&quot;: {
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText,
},
}));
//higlight the dates in highlightedDays arra
const ServerDay = (props) =&gt; {
const { highlightedDays = [], day, outsideCurrentMonth, ...other } = props;
const isSelected =
!props.outsideCurrentMonth &amp;&amp;
highlightedDays.includes(day.format(&quot;YYYY-MM-DD&quot;));
return (
&lt;HighlightedDay
{...other}
outsideCurrentMonth={outsideCurrentMonth}
day={day}
selected={isSelected}
/&gt;
);
};
const SessionBooking = ({ doctor }) =&gt; {
const [value, setValue] = useState(&quot;&quot;);
const [highlightedDays, setHighlitedDays] = useState([
&quot;2023-07-01&quot;,
&quot;2023-07-09&quot;,
&quot;2023-07-21&quot;,
&quot;2024-07-12&quot;,
]);
const today = dayjs();
return (
&lt;Box&gt;
&lt;LocalizationProvider dateAdapter={AdapterDayjs}&gt;
&lt;StaticDatePicker
defaultValue={today}
minDate={today}
maxDate={today.add(1, &quot;month&quot;)}
slots={{
day: ServerDay,
}}
slotProps={{
day: {
highlightedDays,
},
}}
/&gt;
&lt;/LocalizationProvider&gt;
&lt;/Box&gt;
);
};
export default SessionBooking;

<!-- end snippet -->

在MUI StaticDatePicker日历中突出显示日期。

huangapple
  • 本文由 发表于 2023年6月29日 04:13:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定