Ionic React中如何从IonDateTime获取选中日期
解决React中IonDateTime onChange获取选中日期的问题
你代码里的报错是因为沿用了Angular的模板引用写法(#datetime),但React中没有这种直接引用DOM元素的方式。同时你用普通let变量管理日期值,在React函数组件里这会导致状态更新后UI无法同步渲染。下面是两种正确的解决方式:
方法一:通过onChange事件参数获取选中值(推荐)
React中IonDatetime的onChange会触发一个CustomEvent,事件对象的detail.value就是选中的日期值。同时要用useState管理状态,保证UI能随状态更新:
import { useState } from 'react'; import { IonModal, IonContent, IonDatetime } from '@ionic/react'; import { format } from 'date-fns'; // 假设你用date-fns格式化日期 const DateModal: React.FunctionComponent<any> = ({ isOpen, onClose }) => { // 用useState初始化并管理日期状态 const [dateValue, setDateValue] = useState(format(new Date(), 'yyyy-MM-dd') + 'T09:00:00.000Z'); const dateChanged = (event: CustomEvent) => { const selectedDate = event.detail.value; console.log("选中的日期: ", selectedDate); setDateValue(selectedDate); }; return ( <IonModal className="datemodal" isOpen={isOpen}> <IonContent className="dateModalOpen"> <IonDatetime locale="en-GB" value={dateValue} id="datetime" onChange={dateChanged} showDefaultButtons={true} min="1920" max="2022" className="calendar" presentation="date" > <span slot="title">Date of Birth</span> </IonDatetime> </IonContent> </IonModal> ); };
方法二:使用useRef获取DOM元素(不推荐)
如果一定要类似Angular模板引用的方式,可以用React的useRef绑定IonDatetime,然后从ref中读取值:
import { useState, useRef } from 'react'; import { IonModal, IonContent, IonDatetime } from '@ionic/react'; import { format } from 'date-fns'; const DateModal: React.FunctionComponent<any> = ({ isOpen, onClose }) => { const [dateValue, setDateValue] = useState(format(new Date(), 'yyyy-MM-dd') + 'T09:00:00.000Z'); // 创建ref绑定IonDatetime元素 const datetimeRef = useRef<HTMLIonDatetimeElement>(null); const dateChanged = () => { if (datetimeRef.current) { const selectedDate = datetimeRef.current.value; console.log("选中的日期: ", selectedDate); setDateValue(selectedDate); } }; return ( <IonModal className="datemodal" isOpen={isOpen}> <IonContent className="dateModalOpen"> <IonDatetime ref={datetimeRef} locale="en-GB" value={dateValue} id="datetime" onChange={dateChanged} showDefaultButtons={true} min="1920" max="2022" className="calendar" presentation="date" > <span slot="title">Date of Birth</span> </IonDatetime> </IonContent> </IonModal> ); };
关键说明
- React函数组件必须用
useState管理内部状态,普通let变量更新不会触发组件重新渲染,导致UI不同步。 - 优先使用方法一,
IonDatetime的onChange事件已经封装了选中值,通过事件参数获取更符合React的数据流逻辑。
内容的提问来源于stack exchange,提问作者Daniel Morais
相关产品推荐
相关产品推荐

