如何创建具有 3 个输入但映射到 1 个 yup 值的 Formik 和 yup 表单组件?
How do I create a Formik and yup form component which has 3 inputs but maps to 1 yup value?
我基本上是如何在 formik 中创建这个 https://design-system.service.gov.uk/patterns/dates/ 并进行验证的。
所以 3 个字段 day
、month
和 year
将创建合并到一个 {date: [moment]}
以由 yup 验证?
我用了setFieldValue
.
class DatePicker extends React.Component {
state = {
day: '',
month: '',
year: ''
};
updateDateValue = () => {
const {day, month, year} = this.state;
const { field } = this.props;
let momentDate = '';
if (day && month && year) {
const date = moment(`${year}-${month}-${day}T00:00:00+0:00Z`, 'YYYY-MM-DD HH:mm:ss Z');
if (date.isValid()) {
momentDate = date.utc().format();
}
};
this.props.form.setFieldValue(field.name, momentDate, true);
};
handleDayChange = (event) => this.setState({day: event.target.value}, () => this.updateDateValue());
handleMonthChange = (event) => this.setState({month: event.target.value}, () => this.updateDateValue());
handleYearChange = (event) => this.setState({year: event.target.value}, () => this.updateDateValue());
render() {
const {day, month, year} = this.state;
return (
<div>
<div className="datePicker">
<input value={day} label="Day" name="day" onChange={this.handleDayChange} />
<input value={month} label="Month" name="month" onChange={this.handleMonthChange} />
<input value={year} label="Year" name="year" onChange={this.handleYearChange} />
</div>
</div>
);
}
};
我基本上是如何在 formik 中创建这个 https://design-system.service.gov.uk/patterns/dates/ 并进行验证的。
所以 3 个字段 day
、month
和 year
将创建合并到一个 {date: [moment]}
以由 yup 验证?
我用了setFieldValue
.
class DatePicker extends React.Component {
state = {
day: '',
month: '',
year: ''
};
updateDateValue = () => {
const {day, month, year} = this.state;
const { field } = this.props;
let momentDate = '';
if (day && month && year) {
const date = moment(`${year}-${month}-${day}T00:00:00+0:00Z`, 'YYYY-MM-DD HH:mm:ss Z');
if (date.isValid()) {
momentDate = date.utc().format();
}
};
this.props.form.setFieldValue(field.name, momentDate, true);
};
handleDayChange = (event) => this.setState({day: event.target.value}, () => this.updateDateValue());
handleMonthChange = (event) => this.setState({month: event.target.value}, () => this.updateDateValue());
handleYearChange = (event) => this.setState({year: event.target.value}, () => this.updateDateValue());
render() {
const {day, month, year} = this.state;
return (
<div>
<div className="datePicker">
<input value={day} label="Day" name="day" onChange={this.handleDayChange} />
<input value={month} label="Month" name="month" onChange={this.handleMonthChange} />
<input value={year} label="Year" name="year" onChange={this.handleYearChange} />
</div>
</div>
);
}
};