有没有办法解决这个 TypeScript 和 Mantine 不可分配的 DateValue 错误?

问题描述 投票:0回答:1

项目依赖如下:

"dependencies": {
    "@mantine/core": "^7.6.2",
    "@mantine/dates": "^7.6.2",
    "@mantine/form": "^7.6.2",
    "@mantine/hooks": "^7.6.2",
    "dayjs": "^1.11.10",
    "next": "14.1.0",
    "react": "^18",
    "react-dom": "^18",
    "uuid": "^9.0.1"
  }

MantineForm.tsx 文件:

export default function MantineForm() {
    const form = useForm({
        initialValues: {
            visitorName: "",
            firmName: "",
            purposeOfVisit: `${PurposeOfVisit.Subcontractor}`,
            vehicleLicense: "",
            email: "",
            phone: 0,
            visitDateTime: new Date(),
            isSafetyInstructionsGiven: false,
            isGeneralVisitGuideGiven: false,
            isTaskingDocumentReceived: false,
        },

        // validate: {},
    });

在 MantineForm 组件内部,错误就在这里

<DateTimePicker
     value={form.values.visitDateTime}
     onChange={(val) => form.setFieldValue("visitDateTime", val)}
     label="Ziyaret Tarih ve Saati"
     clearable
     valueFormat="DD.MM.YYYY - HH:mm"
     locale="tr"
/>

val
中的
form.setFieldValue("visitDateTime", val)
部分给出了以下错误

“DateValue”类型的参数不可分配给类型的参数 '日期| ((prevValue: 日期) => 日期)'。类型“null”不可分配给 输入“日期| ((prevValue: 日期) => 日期)'.ts(2345)

如何解决此类问题?

reactjs typescript next.js mantine
1个回答
0
投票

它只是意味着

val
可以为 null,这在调用
form.setFieldValue
时不能作为第二个参数。

要解决这个问题: 您可以简单地将 onChnage 转换为:

onChange={(val) => val && form.setFieldValue("visitDateTime", val)}

另一种选择是删除 DateTimePicker 中的

clearable
属性,以便您始终收到一些有效值。

© www.soinside.com 2019 - 2024. All rights reserved.