Mic*_*son 2 datepicker reactjs formik ant-design-pro
我目前正在使用Formik在React中进行预订。我还分别为预订日期和时间合并了Ant Design的Date Picker和Time Picker,但是我很难将值传递回组件。
这是我在表单组件中进行设置的方式(我省略了其他不相关的字段):
const { booking, handleSubmit, mode } = this.props;
...
<Formik
initialValues={booking}
onSubmit={handleSubmit}
render={({errors, touched, isSubmitting}) => (
<Form>
...
<div className="form-group col-sm-4 col-md-6 col-lg-4">
<label htmlFor="booking_date">
Booking Date <span className="required">*</span>
</label>
<DatePicker onChange={ (date, dateString) => setFieldValue('booking_date', dateString)} defaultValue={this.state.bookingDate}
className="form-control" format={this.state.dateFormat} />
</div>
<div className="form-group col-sm-4 col-md-6 col-lg-4">
<label htmlFor="start_time">
Start Time <span className="required">*</span>
</label>
<TimePicker
defaultValue={this.state.startTime}
format={this.state.timeFormat}
className="form-control"
onChange={this.handleStartTimeChange}
minuteStep={5}
id="start_time"
name="start_time"
/>
</div>
Run Code Online (Sandbox Code Playgroud)
这是处理时间变化(仅设置状态)的函数:
handleStartTimeChange(time) {
this.setState({
startTime: time
});
}
Run Code Online (Sandbox Code Playgroud)
然后在父级上,组件的设置如下:
<BookingForm
show={true}
booking={null}
handleSubmit={this.saveBooking.bind(this)}
mode="add"
/>
Run Code Online (Sandbox Code Playgroud)
而且该saveBooking功能只需通过控制台注销参数即可。但是,它永远只能注销的其他领域,如firstname,surname和email。日期被完全忽略了,我不知道如何获取表单来识别它们-我什至尝试创建一个Formik隐藏字段来在提交时复制日期值,但它仍然忽略它。字段名称和ID正确,并且与其他所有数据库都相关联,因此我不明白为什么它不读取该数据?
简单地说,你需要利用蚂蚁设计的Form.Item一个Formik内Field的component道具。
您也可以添加其他Antd表单项,但是有一些怪癖。因此,我只建议使用其中一个(而不是两个)。
工作示例:https : //codesandbox.io/s/4x47oznvvx
components / AntFields.js(创建两个不同onChange函数的原因是,其中一个ant组件传递了event(event.target.value),而另一个则传递了value-不幸的是,在Formik与一起使用时有一个怪癖Antd)
import map from "lodash/map";
import React from "react";
import { DatePicker, Form, Input, TimePicker, Select } from "antd";
const FormItem = Form.Item;
const { Option } = Select;
const CreateAntField = Component => ({
field,
form,
hasFeedback,
label,
selectOptions,
submitCount,
type,
...props
}) => {
const touched = form.touched[field.name];
const submitted = submitCount > 0;
const hasError = form.errors[field.name];
const submittedError = hasError && submitted;
const touchedError = hasError && touched;
const onInputChange = ({ target: { value } }) =>
form.setFieldValue(field.name, value);
const onChange = value => form.setFieldValue(field.name, value);
const onBlur = () => form.setFieldTouched(field.name, true);
return (
<div className="field-container">
<FormItem
label={label}
hasFeedback={
(hasFeedback && submitted) || (hasFeedback && touched) ? true : false
}
help={submittedError || touchedError ? hasError : false}
validateStatus={submittedError || touchedError ? "error" : "success"}
>
<Component
{...field}
{...props}
onBlur={onBlur}
onChange={type ? onInputChange : onChange}
>
{selectOptions &&
map(selectOptions, name => <Option key={name}>{name}</Option>)}
</Component>
</FormItem>
</div>
);
};
export const AntSelect = CreateAntField(Select);
export const AntDatePicker = CreateAntField(DatePicker);
export const AntInput = CreateAntField(Input);
export const AntTimePicker = CreateAntField(TimePicker);
Run Code Online (Sandbox Code Playgroud)
components / FieldFormats.js
export const dateFormat = "MM-DD-YYYY";
export const timeFormat = "HH:mm";
Run Code Online (Sandbox Code Playgroud)
components / ValidateFields.js
import moment from "moment";
import { dateFormat } from "./FieldFormats";
export const validateDate = value => {
let errors;
if (!value) {
errors = "Required!";
} else if (
moment(value).format(dateFormat) < moment(Date.now()).format(dateFormat)
) {
errors = "Invalid date!";
}
return errors;
};
export const validateEmail = value => {
let errors;
if (!value) {
errors = "Required!";
} else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(value)) {
errors = "Invalid email address!";
}
return errors;
};
export const isRequired = value => (!value ? "Required!" : "");
Run Code Online (Sandbox Code Playgroud)
组件/RenderBookingForm.js
import React from "react";
import { Form, Field } from "formik";
import { AntDatePicker, AntInput, AntSelect, AntTimePicker } from "./AntFields";
import { dateFormat, timeFormat } from "./FieldFormats";
import { validateDate, validateEmail, isRequired } from "./ValidateFields";
export default ({ handleSubmit, values, submitCount }) => (
<Form className="form-container" onSubmit={handleSubmit}>
<Field
component={AntInput}
name="email"
type="email"
label="Email"
validate={validateEmail}
submitCount={submitCount}
hasFeedback
/>
<Field
component={AntDatePicker}
name="bookingDate"
label="Booking Date"
defaultValue={values.bookingDate}
format={dateFormat}
validate={validateDate}
submitCount={submitCount}
hasFeedback
/>
<Field
component={AntTimePicker}
name="bookingTime"
label="Booking Time"
defaultValue={values.bookingTime}
format={timeFormat}
hourStep={1}
minuteStep={5}
validate={isRequired}
submitCount={submitCount}
hasFeedback
/>
<Field
component={AntSelect}
name="bookingClient"
label="Client"
defaultValue={values.bookingClient}
selectOptions={values.selectOptions}
validate={isRequired}
submitCount={submitCount}
tokenSeparators={[","]}
style={{ width: 200 }}
hasFeedback
/>
<div className="submit-container">
<button className="ant-btn ant-btn-primary" type="submit">
Submit
</button>
</div>
</Form>
);
Run Code Online (Sandbox Code Playgroud)
组件/BookingForm.js
import React, { PureComponent } from "react";
import { Formik } from "formik";
import RenderBookingForm from "./RenderBookingForm";
import { dateFormat, timeFormat } from "./FieldFormats";
import moment from "moment";
const initialValues = {
bookingClient: "",
bookingDate: moment(Date.now()),
bookingTime: moment(Date.now()),
selectOptions: ["Mark", "Bob", "Anthony"]
};
const handleSubmit = formProps => {
const { bookingClient, bookingDate, bookingTime, email } = formProps;
const selectedDate = moment(bookingDate).format(dateFormat);
const selectedTime = moment(bookingTime).format(timeFormat);
alert(
`Email: ${email} \nSelected Date: ${selectedDate} \nSelected Time: ${selectedTime}\nSelected Client: ${bookingClient}`
);
};
export default () => (
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
render={RenderBookingForm}
/>
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3515 次 |
| 最近记录: |