问题描述
我对如何处理react-dates [DateRangePicker] onDatesChange和onFocusChange感到困惑,因为它们每个都有两个值. onDatesChange 应该能够设置多个值,即开始日期和结束日期.
I'm confused about how to handle react-dates[DateRangePicker] onDatesChange and onFocusChange because they have two values each.onDatesChange should be able to set multiple values i.e both start date and end date.
我正在尝试使用formik在daterangepicker周围构建自定义包装.
I was trying to build a custom wrapper around the daterangepicker with formik.
检查控制台中的错误
`<div className="form-group">
<label>DatePickerWithFormik</label>
<Field component={DatePickerWithFormik} name="DatePickerWithFormik"
className="form-control" />
</div>`
`export const DatePickerWithFormik = ({ startDateId, endDateId, form: { setFieldValue, setFieldTouched }, field, ...props }) => {
const [focused, setFocused] = useState(null); // this will be removed
return(
<div>
{/* {console.log('Inside datpicer', field.name)} */}
<DateRangePicker
{...props}
startDateId="startDateId"
endDateId="endDateId"
onDatesChange={(value) =>
field.onChange(setFieldValue(field.name, value) )}
onFocusChange={focused => setFocused(focused)}
focusedInput={focused}
startDate={field.startDate}
endDate={field.endDate}
/>
{/* {console.log(field)} */}
</div>
);
};
`
- 预期结果:应该能够将开始日期和结束日期都保存在本地状态,并将其显示在屏幕上.
请参考工作链接: https://codesandbox.io/s/l72w6n8l0m
推荐答案
您需要使用startDate和endDate初始化表单:
You need to initialize your form with startDate and endDate:
const formInitialValues = {
// DatePickerWithFormik: null
startDate: null,
endDate: null
};
然后像这样设置onDatesChange
:onDatesChange={handleDatesChange}
并在handleDatesChange
函数中更新值:
then set the onDatesChange
like this: onDatesChange={handleDatesChange}
and in the handleDatesChange
function update the values:
const handleDatesChange = ({ startDate, endDate }) => {
setStartDate(startDate);
setEndDate(endDate);
setFieldValue("startDate", startDate);
setFieldValue("endDate", endDate);
};
演示: https://codesandbox.io/s/m39w2onqky
修改:
由于您不会使用任何状态,因此可以使用如下形式的values
属性:
As you wouldn't use any state you can use the form values
property like this:
<DateRangePicker
startDate={values.startDate}
startDateId="tata-start-date"
endDate={values.endDate}
endDateId="tata-end-date"
onDatesChange={handleDatesChange}
focusedInput={focusedInput}
onFocusChange={focusedInput => setFocusedInput(focusedInput)}
/>
工作演示: https://codesandbox.io/s/ppv546qxz7
这篇关于有没有人成功地将react-dates DateRangePicker与formik集成在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!