전제
형식을 지정하고 입력 유형 인 datetime-local에 기본값으로 설정 한 날짜가 있습니다. onChange
입력의 경우 새로 선택한 날짜 / 시간을 형식화하고 상태로 저장하고 싶습니다. 그러나 작동하지 않습니다. 아래는 내 코드입니다.
DateTime 구성 요소
import React from "react";
const DateTime = ({ value, onChange }) => {
return <input type="datetime-local" value={value} onChange={onChange} />;
};
export default DateTime;
App.js
import React, { useState, useEffect } from "react";
import DateTime from "./DateTime";
import moment from "moment";
export default function App() {
const [defaultDate, setDefaultDate] = useState("08/08/2020 10:00:00");
// The above static date string comes from a context provider. Here just for the example
const [plannedDate, setPlannedDate] = useState();
const formatPlannedDate = (date) => {
const d = moment(date).format("M/DD/YYYY HH:mm:ss");
return d;
};
const handleOnChange = (value) => {
setPlannedDate(formatPlannedDate(value));
console.log(plannedDate);
};
useEffect(() => {
setDefaultDate(moment(defaultDate).format("YYYY-MM-DD[T]HH:mm:ss"));
}, []);
return (
<div className="App">
<DateTime
value={defaultDate}
onChange={(e) => handleOnChange(e.target.value)}
/>
</div>
);
}
작동했지만 setPlannedDate
by useState
가 비동기식이므로 즉시 영향을 미치지 않습니다. 따라서 변경 사항을 확인하려면 useEffect
대신
// ...
const handleOnChange = (value) => {
setPlannedDate(formatPlannedDate(value));
};
useEffect(() => {
console.log(plannedDate);
}, [plannedDate])
// ...
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다