gpt4 book ai didi

reactjs - 是否可以将 react-datepicker 与 react 钩子(Hook)形式一起使用?

转载 作者:行者123 更新时间:2023-12-04 11:08:46 24 4
gpt4 key购买 nike

是否可以将 react-datepicker 与 react 钩子(Hook)形式一起使用?我尝试了以下示例:

https://codesandbox.io/s/awesome-shape-j0747?fontsize=14&hidenavigation=1&theme=dark

但没有运气。

import React, { useState } from "react";
import "./styles.css";
import { useForm } from "react-hook-form";
import { Row, Col, Form, FormGroup, Label, Input, Button } from "reactstrap";
import DatePicker from "react-datepicker";

export default function App() {
const { register, handleSubmit } = useForm();
const [startDate, setStartDate] = useState();
const [result, setResult] = useState();

const onSearch = event => {
setResult(event);
};

return (
<div className="App">
<Form onSubmit={handleSubmit(onSearch)}>
<Row>
<Col>
<FormGroup>
<Input
type="number"
name="account"
id="account"
placeholder="AccountId"
innerRef={register({ required: true, maxLength: 20 })}
/>
</FormGroup>
</Col>
</Row>

<Row>
<Col>
<DatePicker
innerRef={register}
name="datetime"
className={"form-control"}
selected={startDate}
onChange={date => setStartDate(date)}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
timeCaption="time"
dateFormat="MM-dd-yyyy h:mm"
/>
</Col>
</Row>

<Button>Submit</Button>
</Form>
<div>{JSON.stringify(result)}</div>
</div>
);
}

最佳答案

请查看 Controller 文档:https://react-hook-form.com/api/#Controller
我们正在维护一个代码框示例,用于托管大多数外部组件 UI 库的实现:https://codesandbox.io/s/react-hook-form-controller-079xx

<Controller
as={ReactDatePicker}
control={control}
valueName="selected" // DateSelect value's name is selected
onChange={([selected]) => selected}
name="ReactDatepicker"
className="input"
placeholderText="Select date"
/>
编辑
使用最新版本的 react-hook-form 这是使用渲染的 Controller 实现:
            <Controller
name={name}
control={control}
render={({ onChange, value }) => (
<DatePicker
selected={value}
onChange={onChange}
/>
)}
/>

关于reactjs - 是否可以将 react-datepicker 与 react 钩子(Hook)形式一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60864610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com