如何根据JSON阵列禁用MUI中的某些日子和日期datePicker?

发布于 2025-01-25 06:32:09 字数 1029 浏览 3 评论 0 原文

我拥有Laravel应用程序,该应用程序返回日期和一周中的日期的响应,

例如,在datepicker中应禁用,例如,当i console.log() it ['' 2022-05-08','2022-05-11','2022-05-19']

,这是i console.log() it 时,这是daysoff常数[3,6]

因此,我如何禁用返回日期和日期(在这种情况下为周三和周日)

    useEffect(() => {
      axios.get(bookingUrl).then((response) => {
        setDaysOff(response.data.daysOff);
        setDatesOff(response.data.datesOff);
        setBooked(response.data.booked);
      })
    }, []);

<LocalizationProvider locale={hr} dateAdapter={AdapterDateFns}>
            <DatePicker
            label="Date"
            disablePast={true}
            minDate={minDate}
            maxDate={maxDate}
            value={date}
            shouldDisableDate={//What do i to here
            }
            onChange={(newDate) => {
            setDate(newDate);
            }}
            renderInput={(params) => <TextField {...params} />}

I have Laravel app that returns a json response of dates and days of the week that should be disabled in the datepicker

For example this is my datesOff constant when I console.log() it ['2022-05-08', '2022-05-11', '2022-05-19']

And This is daysOff constant when I console.log() it [3, 6]

So how do I disable both returned dates and days(wednesday and sunday in this case)

    useEffect(() => {
      axios.get(bookingUrl).then((response) => {
        setDaysOff(response.data.daysOff);
        setDatesOff(response.data.datesOff);
        setBooked(response.data.booked);
      })
    }, []);

<LocalizationProvider locale={hr} dateAdapter={AdapterDateFns}>
            <DatePicker
            label="Date"
            disablePast={true}
            minDate={minDate}
            maxDate={maxDate}
            value={date}
            shouldDisableDate={//What do i to here
            }
            onChange={(newDate) => {
            setDate(newDate);
            }}
            renderInput={(params) => <TextField {...params} />}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

汐鸠 2025-02-01 06:32:09

感谢 dmitriif 代码工作正常,除了代码的一个问题是日期请勿禁用数组的日期,例如日期:2020-05-19,它将禁用2020-05-20,以解决您需要更新一行代码:

const stringifiedDate = date.toISOString().slice(0, 10);

to:

const stringifiedDate = dayjs(date).format('YYYY-MM-DD');

install dayjs 并在您的文件中导入。你很好。

再次感谢 dmitriif

Appreciate the answer from Dmitriif the code is working fine except one issue with the code is the array of dates not disabling the dates from the array such as date: 2020-05-19 and It's disabled the 2020-05-20 to fix that you need to update the one line of code:

const stringifiedDate = date.toISOString().slice(0, 10);

to:

const stringifiedDate = dayjs(date).format('YYYY-MM-DD');

install dayjs and import in your file. and you are good to go.

thanks again to Dmitriif

翻了热茶 2025-02-01 06:32:09

datepicker renderday> renderday 可以用来自定义日历的日间单元格。它需要3个参数,第一个是日期对象,我们可以用来将其与应禁用的一系列日期进行比较:

  const dates = ["2022-05-08", "2022-05-11", "2022-05-19"];

  const customDayRenderer = (
    date: Date,
    selectedDates: Array<Date | null>,
    pickersDayProps: PickersDayProps<Date>
  ) => {
    const stringifiedDate = date.toISOString().slice(0, 10);
    if (dates.includes(stringifiedDate)) {
      return <PickersDay {...pickersDayProps} disabled />;
    }
    return <PickersDay {...pickersDayProps} />;
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <DatePicker
        label="Basic example"
        value={value}
        onChange={(newValue) => {
          setValue(newValue);
        }}
        renderInput={(params) => <TextField {...params} />}
        renderDay={customDayRenderer}
      />
    </LocalizationProvider>
  );

demo

DatePicker has renderDay prop which we can use to customize the day cells of the calendar. It takes 3 arguments, the first one is the Date object, which we can use to compare with the array of dates that should be disabled:

  const dates = ["2022-05-08", "2022-05-11", "2022-05-19"];

  const customDayRenderer = (
    date: Date,
    selectedDates: Array<Date | null>,
    pickersDayProps: PickersDayProps<Date>
  ) => {
    const stringifiedDate = date.toISOString().slice(0, 10);
    if (dates.includes(stringifiedDate)) {
      return <PickersDay {...pickersDayProps} disabled />;
    }
    return <PickersDay {...pickersDayProps} />;
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <DatePicker
        label="Basic example"
        value={value}
        onChange={(newValue) => {
          setValue(newValue);
        }}
        renderInput={(params) => <TextField {...params} />}
        renderDay={customDayRenderer}
      />
    </LocalizationProvider>
  );

Demo

蓝海似她心 2025-02-01 06:32:09

我的答案是基于DMITRIIF的答案,但它已经更改,因为它在选择日期的过程中导致了许多渲染。

const customDayRenderer = (
    date: Date,
    selectedDates: Array<Date | null>,
    pickersDayProps: PickersDayProps<Date>
) => {
    amountOfExercises.forEach(day => {
        selectedDates.push(new Date(day.exerciseDate))
    });

    return <PickersDay {...pickersDayProps}  sx={{
        [`&&.${pickersDayClasses.selected}`]: {
          backgroundColor: "#EBEBE4",
          cursor: 'not-allowed'
        }
      }} />;
};

<DatePicker
   disablePast={true}
   label="Exercise Date"
   **renderDay={customDayRenderer}**
   value={dateValue}
   onChange={(newDateValue) => {
     setNewDateValue(newDateValue);
   }}
   renderInput={(params) => <TextField {...params} />}
/>

MANESOFECERCISE 是一个JSON数组,在 foreach 内。我正在提取要禁用的日期,然后将其推到 selected Dates 数组。

执行此操作后,您会注意到您想要禁用的日期的背景颜色已更改,这意味着 datePicker “知道”应该选择哪些日期。

为了让用户有一种感觉,即 selected Dates 无法用于(禁用)选择,我添加了 sx 属性,该属性提供了 lightgray 背景颜色和不允许的光标。

我的代码中的 customdayrender 内部的日期变量永远不会读取

My answer is based on the answer by Dmitriif but it has been changed because it caused many renders through the process of selecting a date.

const customDayRenderer = (
    date: Date,
    selectedDates: Array<Date | null>,
    pickersDayProps: PickersDayProps<Date>
) => {
    amountOfExercises.forEach(day => {
        selectedDates.push(new Date(day.exerciseDate))
    });

    return <PickersDay {...pickersDayProps}  sx={{
        [`&&.${pickersDayClasses.selected}`]: {
          backgroundColor: "#EBEBE4",
          cursor: 'not-allowed'
        }
      }} />;
};

<DatePicker
   disablePast={true}
   label="Exercise Date"
   **renderDay={customDayRenderer}**
   value={dateValue}
   onChange={(newDateValue) => {
     setNewDateValue(newDateValue);
   }}
   renderInput={(params) => <TextField {...params} />}
/>

The amountOfExercises is a JSON array and inside the forEach. I'm extracting the date I want to disable and push it to the selectedDates array.

After doing this you will notice that the background color of the dates you want disable had changed meaning the DatePicker "knows" what dates are supposed to be selected.

In order to give the user a feeling that the selectedDates are not available for the (disabled) selection I've added the sx attribute which gives a lightgray background color and a cursor which is not allowed.

The date variable inside customDayRender in my code is never read but when trying to delete it I've got an error that the renderDay method can't find the day to render

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文