我正在嘗試在我的 react/date-fns 應用程式中使用此 codepen中的代碼。
import {useEffect, useRef, useState} from 'react'
import {add, sub, format, parse} from 'date-fns'
const timeRegExp = /([01][0-9]|2[0-3])[0-5][0-9]/
const Time = () => {
const refs = useRef([])
const [values, setValues] = useState([])
useEffect(() => {
refs.current.forEach((input, i) => {
input.addEventListener('keydown', (e: any) => {
if (e.keyCode === 37) {// left arrow
if (i !== 0) refs.current[i - 1].focus()
} else if (e.keyCode === 39) {// right arrow
if (i !== 3) refs.current[i 1].focus()
} else if (/48|49|50|51|52|53|54|55|56|57/.test(e.keyCode)) {// 0 ~ 9
const time = [0, 1, 2, 3].map(i => {
return i === i ? String.fromCharCode(e.keyCode) : refs.current[i].value
}).join('')
if (timeRegExp.test(time)) {
refs.current[i].value = String.fromCharCode(e.keyCode)
if (i !== 3) refs.current[i 1].focus()
}
} else if (e.keyCode === 8) {// delete / backspace
refs.current[i].value = 0
if (i !== 0) refs.current[i - 1].focus()
} else if (e.keyCode === 38) {// up arrow
// if (i === 0 && refs.current[0].value === '2') {
//
// } else {
// let time = [0, 1, 2, 3].map(i => refs.current[i].value).join('')
// time = moment(time, 'HHmm').add(i % 2 ? 1 : 10, Math.floor(i / 2) ? 'm' : 'h').format('HHmm').split('');
// [0, 1, 2, 3].forEach(i => refs.current[i].value = time[i])
// }
} else if (e.keyCode === 40) {// down arrow
// if (i === 0 && refs.current[0].value === '0') {
// } else {
// let time = [0, 1, 2, 3].map(i => refs.current[i].value).join('')
// time = moment(time, 'HHmm').subtract(i % 2 ? 1 : 10, Math.floor(i / 2) ? 'm' : 'h').format('HHmm').split('');
// [0, 1, 2, 3].forEach(i => refs.current[i].value = time[i])
// }
}
e.preventDefault()
})
})
// input.addEventListener('keydown', e => {}))
}, [])
return <div>
<input ref={e => refs.current[0] = e} defaultValue={0}/>
<input ref={e => refs.current[1] = e} defaultValue={0}/>
<span>:</span>
<input ref={e => refs.current[2] = e} defaultValue={0}/>
<input ref={e => refs.current[3] = e} defaultValue={0}/>
</div>
}
export default Time
如何將注釋掉的代碼轉換為使用date-fns?
uj5u.com熱心網友回復:
你必須做移植作業,沒有通用的方法。雖然它相當容易。例如,對于代碼的一部分
// let time = [0, 1, 2, 3].map(i => refs.current[i].value).join('')
// time = moment(time, 'HHmm').add(i % 2 ? 1 : 10, Math.floor(i / 2) ? 'm' : 'h').format('HHmm').split('');
// [0, 1, 2, 3].forEach(i => refs.current[i].value = time[i])
這將是
let time = [0, 1, 2, 3].map(i => refs.current[i].value).join('')
const parsed = parse(time, "HHmm");
console.log("parsed", parsed)
const addF = Math.floor(i / 2) ? addMinutes : addHours;
const added = addF(parsed, i % 2 ? 1 : 10);
const formatted = format(added, "HHmm");
time = formatted.split('');
[0, 1, 2, 3].forEach(i => refs.current[i].value = time[i])
為了便于閱讀,代碼被拆分為分配,但如果您更喜歡 oneliners,您可以使用 lodash compose date-fns/fp 鏈接這些函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/481378.html
上一篇:如何在JS中增加這個日期字串'2022-05-06'中的日期
下一篇:旋轉檔案名中已有日期時間的檔案
