[英]How to convert moment.js to date-fns
我正在尝试在我的 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
?
你必须做移植工作,没有通用的方法。 虽然它相当容易。 例如,对于代码的一部分
// 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 链接这些函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.