我正在尝试在呈现编辑表单组件时填充material-ui datepicker字段的值,我可以在控制台中看到date对象正在正确创建,但是它没有传递到状态,不知道是什么我做错了。
这里是组件
function DatePickerField(props) {
const { field , studentValues, control} = props;
const classes = useStyle();
const [date, setDate] = useState(null);
const handleChange = (date) => {
setDate(date)
}
// Check if the input name of the field we get from knack match the input name of the form and if yes display the value
useEffect(() => {
if (studentValues) {
const dataStudentArranged = DataStudent(studentValues);
dataStudentArranged.forEach((card) => {
card.cardValues.forEach((cardValue) => {
if (cardValue.formName === field.formName) {
const dateObject = fromUnixTime(cardValue.value/1000)
setDate(dateObject)
console.log('date object =>',dateObject)
}
})
})
}
}, []);
return (
<TableRow>
<TableCell>
<Controller defaultValue={date} name={field.formName} control = {control}
as = {
<DatePicker
className={classes.datePicker}
inputVariant = "outlined"
label={field.label}
value={date}
onChange={handleChange}
autoOk
variant="inline"
format= "dd, MMMM yyyy"
size="small"
/>
}
/>
</TableCell>
</TableRow>
)
}
export default DatePickerField
谢谢!
答案 0 :(得分:1)
问题出在react-hook-form上,即使在使用useEfect之后,它也始终传递默认值,这个问题帮助我解决了问题:https://stackoverflow.com/a/62243132/9813493
基本上,当在控制道具中使用react-hook-form时,我们应该使用setValue函数https://react-hook-form.com/api#setValue