[英]Datepicker component breaking an edit screen, using @unform and react-datepicker
I created the following component to select dates in UnForm:我在 UnForm 中为 select 日期创建了以下组件:
export default function DatePickerInput({ name, ...rest }) {
const datepickerRef = useRef(null);
const { fieldName, defaultValue = '', registerField } = useField(name);
const [date, setDate] = useState(defaultValue || null);
useEffect(() => {
registerField({
name: fieldName,
ref: datepickerRef.current,
path: 'props.selected',
});
}, [fieldName, registerField]);
return (
<Label htmlFor={fieldName}>
<UnInput>
<ReactDatePicker
ref={datepickerRef}
selected={date}
onChange={setDate}
dateFormat="dd/MM/yyyy"
placeholderText="dd/mm/aaaa"
writable="true"
{...rest}
/>
</UnInput>
</Label>
);
}
To save records the component is working normally, loading and saving the date I selected.要保存记录,组件工作正常,加载并保存我选择的日期。 When I am going to edit a record, when trying to load the date in the initial load, the page is broken and the following error is displayed:
当我要编辑一条记录时,尝试在初始加载中加载日期时,页面损坏并显示以下错误:
Unhandled Rejection (TypeError): Cannot assign to read only property 'selected' of object '#<Object>'
If I comment out the line path: 'props.selected'
, in useEffect ()
the screen is not broken, but the date is not filled in the component.如果我注释掉 line
path: 'props.selected'
,在useEffect ()
中屏幕没有坏,但是组件中没有填写日期。 How do it work?它是如何工作的?
Issue:问题:
formRef.current.setFieldValue('birthday',value)
this will try to set value on provided path
, in our case provided path is props.selected
. formRef.current.setFieldValue('birthday',value)
这将尝试在提供的path
上设置值,在我们的例子中提供的路径是props.selected
。
And props.selected
is read-only property so you can't set value on props
hence the error.并且
props.selected
是只读属性,因此您无法在props
上设置值,因此会出现错误。
useEffect(() => {
registerField({
name: fieldName,
ref: datepickerRef.current,
path: 'props.selected', // <---- this is props, and it's readonly
clearValue: (ref) => {
ref.clear();
},
});
}, [fieldName, registerField]);
Solution:解决方案:
You can remove the path
and use getter
and setter
methods, named as getValue
and setValue
:您可以删除
path
并使用getter
和setter
方法,命名为getValue
和setValue
:
setValue
: to set the initial value or whatever passed from setFieldValue
setValue
:设置初始值或从setFieldValue
传递的任何值
getValue
: to get value on submit getValue
:在提交时获得价值
useEffect(() => {
registerField({
name: fieldName,
ref: datepickerRef.current,
clearValue: ref => {
ref.clear();
},
setValue: (e, v) => {
setDate(new Date(v)); // <---- Setting up default value
},
getValue: () => {
return datepickerRef.current.props.selected; // to get selected value from Date picker's props
// OR
return Date.toString(); // to get selected value from state it self
}
});
}, [fieldName, registerField]);
WORKING DEMO :工作演示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.