【问题标题】:react-hook-form and react-datetime: How to set the time to moment() from a buttonreact-hook-form 和 react-datetime:如何从按钮将时间设置为 moment()
【发布时间】:2021-11-06 03:29:16
【问题描述】:

我在 react-hook-form 中使用 react-datetime

我希望用户使用按钮Immediate 轻松将时间设置为当前时间。而不是手动选择当前时间。

我正在尝试以下方法


const [currentDateTime, setcurrentDateTime] = useState(null);
<Controller
    name="resetDateTime"
    control={control}
    required
    render={({ field }) => (
        <Datetime
            onChange={setcurrentDateTime}
            inputProps={{
                placeholder: "MM-DD-YYYY HH:mm",
            }}
            value={currentDateTime}
            viewMode="time"
        />
    )}
/>
<Button color="primary" className="ml-1" onClick={() => setcurrentDateTime(moment())}>
    {"Immediate"}
</Button>

问题是 onSubmit 我得到的 react-hook-form resetDateTime = undefined

如何正确实施。所以我可以使用Immediate 按钮并提交表单并获取resetDateTime

【问题讨论】:

    标签: react-hook-form react-datetime


    【解决方案1】:

    您将 RHF 与您当地的州 currentDateTime 混合在一起,并且没有链接。字段到 RHF,因为您缺少将 field 对象传播到您的 &lt;Datetime /&gt; 组件。

    正确的方法是使用 RHF 的 setValue 更新您的 resetDateTime 字段并摆脱 useState 挂钩。

    const { control, handleSubmit, setValue } = useForm();
    
    <Controller
        name="resetDateTime"
        control={control}
        required
        render={({ field }) => (
            <Datetime
                {...field}
                inputProps={{
                    placeholder: "MM-DD-YYYY HH:mm",
                }}
                viewMode="time"
            />
        )}
    />
    
    <Button color="primary" className="ml-1" onClick={() => setValue("resetDateTime", moment())}>
        {"Immediate"}
    </Button>
    

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 2020-12-26
      • 2022-12-21
      • 2021-08-10
      • 1970-01-01
      • 2021-03-29
      • 2023-01-26
      • 2017-12-03
      • 1970-01-01
      相关资源
      最近更新 更多