[英]How to display date on react-calendar using DateTime value from database
我對 React 很陌生,我通過搜索找到了 react-calendar,並將其用作我的應用程序的日期選擇器。 當我在我的應用程序上保存一個新實體時,它會將 react-calendar 中的日期保存到我的數據庫中。 但是當我在前端更新實體時,有沒有辦法在反應日歷上顯示日期時間值? 我知道格式錯誤,所以它會引發錯誤。 如何正確格式化 react-calendar 以接受日期時間/日期值並可能在日期選擇器上直觀地顯示它?
這是我的控制台日志當前顯示的內容:
export function PatientForm(props) { const [PatientId, setPatientId] = useState(props.patient.patientId); const [FirstName, setFirstName] = useState(props.patient.firstName); const [LastName, setLastName] = useState(props.patient.lastName); const dateReceived = props.patient.dateOfBirth; const formattedDateOfBirth = moment(dateReceived).format('MMMM Do YYYY'); console.log('Got the datetime properly: ' + props.patient.dateOfBirth); console.log('date received: ' + dateReceived); console.log('formatted DOB: ' + formattedDateOfBirth); const [DateOfBirth, setDateOfBirth] = useState(formattedDateOfBirth); const [Gender, setGender] = useState(props.patient.gender); const [DoctorId, setDoctorId] = useState(props.patient.doctorId); const handleSubmit = (e) => { e.preventDefault(); props.submit({ PatientId, FirstName, LastName, DateOfBirth, Gender, DoctorId }); }
export function UpdatePatient(props) { const { patientId } = useParams(); const [patient, setPatient] = useState(); const navigate = useNavigate(); useEffect(() => { fetch('patient/edit/' + patientId).then(res => res.json()).then(p => setPatient(p)); }, []); const handleSubmit = (patient) => { fetch('patient/update', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patient) } ); navigate('/listpatients'); } //FIX ME: NOT RENDERING REACT-CALENDAR PROPERLY return ( patient? <PatientForm patient={patient} submit={handleSubmit} />: <div>...loading</div> ); }
解決了
我必須像這樣將道具傳遞給一個新的日期,並為 DateOfBirth 聲明單獨的變量:
const [value, setValue] = useState(new Date(props.patient.dateOfBirth));
const [DateOfBirth, setDateOfBirth] = useState(props.patient.dateOfBirth);
然后在 Calendar 標記中,我必須使用 reac-calendar "defaultValue" 中的關鍵字,然后傳入之前聲明的值。
<Calendar calendarType="US" defaultValue={value} onChange={onChange} />
我還創建了一個助手 function 在 onChange 內部做一些事情,基於 react-calendar 的文檔:
function onChange(DateOfBirth) {
setDateOfBirth(DateOfBirth);
}
在此處查看我的沙箱:解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.