【发布时间】:2021-03-28 22:16:43
【问题描述】:
有没有人使用带有日期/时间选择器的 react-hook-form 并使用 Material-UI 的示例?我已经能够使用具有“本地日期时间”类型的 Mui TextField 来实现,并且可以设置日期/时间,但是在使用默认值输入表单时,我无法在字段中显示时间戳react-hook-form 的值;也就是说,日期/时间值不会出现在选择器中。在手动设置日期/时间值并提交表单后,该值将正确绑定到 react-hook-form“数据”对象。我的代码中的一些片段如下。我用省略号 (...) 替换了不相关的代码。
import React from 'react';
import { Controller, useForm } from 'react-hook-form';
import { TextField } from '@material-ui/core';
...
interface IMyFormProps {
name: string;
description: string;
occurrenceTimestamp: Date;
}
...
const MyForm: React.FC<IMyFormProps> = (props: IMyFormProps) => {
...
// set up details for ReactHookForm
const { register, control, formState, handleSubmit, errors } = useForm({
defaultValues: {
name: props.name,
description: props.description,
occurrenceTimestamp: props.occurrenceTimestamp
},
mode: "all"
});
...
return (
<form onSubmit=...
// a text input for Name
<TextField
inputRef={register({ required: true })}
name="name"
label="Name"
...
/>
// a text input for Description
<TextField
inputRef={register({ required: true })}
name="description"
label="Description"
...
/>
// The Date/Time Picker
<Controller
render={(props) =>
<TextField
{...props}
type="datetime-local"
label="Occurrence Date/Time"
/>
}
name="occurrenceTimestamp"
control={control}
>
</Controller>
>
</form>
)
}
【问题讨论】:
-
你好@thomas 你能粘贴在控制器代码下吗?这里
标签: reactjs material-ui datetimepicker react-hook-form