由于它提供的性能,我最近开始使用react,所以我不习惯这个新框架。我一直在搜索这个确切的话题,但没有找到答案。
虽然问题很简单,(只想返回所选日期)。
这是我目前正在尝试做的:
let dateValue = format(new Date(), 'yyyy-MM-dd')+ 'T09:00:00.000Z';
const dateChanged = (value: any) => {
console.log("value: ", value);
dateValue = value;
};
const DateModal: React.FunctionComponent<any> = ({ isOpen, onClose }) => {
return (
<IonModal className="datemodal" isOpen={isOpen}>
<IonContent className="dateModalOpen">
<IonDatetime
locale="en-GB"
value={dateValue}
id="datetime"
onChange={() => dateChanged(datetime)}
showDefaultButtons={true}
min="1920"
max="2022"
className="calendar"
presentation="date"
>
<span slot="title">Date of Birth</span>
</IonDatetime>
</IonContent>
</IonModal>
);
};
我收到一个错误的"onChange"(找不到名称'datetime'.),这是我过去在Angular中所做的。我试着用"id=datetime"来使用模板引用,在Angular中是"#datetime"。这样做将在onChange事件中工作。
我如何使它工作?提前感谢!
您只需要使用ionOnChange
处理程序:
<IonDatetime presentation="date"
id="datetime"
onIonChange={(e) => console.log(e)}>
</IonDatetime>
解决。在react中你可以使用"Controller"从IonDateTime获取数据,如下所示:
const {
handleSubmit,
control,
setValue,
register,
getValues,
formState: { errors },
} = useForm({
defaultValues: {
fullname: "",
date: "",
gender: "MALE",
email: "",
},
});
console.log(getValues());
/**
*
* @param data
*/
const onSubmit = (data: any) => {
alert(JSON.stringify(data, null, 2));
};
const [ionDate, setIonDate] = useState("");
const dateChanged = (value: any) => {
let formattedDate = format(parseISO(value), "dd-MM-yyyy").replace(
/-/g,
"/"
);
setIonDate(formattedDate);
setshowDate({ isOpen: false });
};
const DateModal: React.FunctionComponent<any> = ({ isOpen }) => {
console.log(isOpen);
return (
<IonModal className="datemodal" isOpen={isOpen}>
<IonContent className="dateModalOpen">
<Controller
render={({ field }) => (
<IonDatetime
value={field.value}
onIonChange={(e) => dateChanged(e.detail.value)}
locale="en-GB"
onChange={dateChanged}
showDefaultButtons={true}
onIonCancel={() => setshowDate({ isOpen: false })}
min="1920"
max="2022"
className="calendar"
presentation="date"
>
<span slot="title">Date of Birth</span>
</IonDatetime>
)}
control={control}
name="date"
rules={{ required: "This is a required field" }}
/>
<IonButton type="submit">submit</IonButton>
</IonContent>
</IonModal>
);
};
};