我使用 react 封装了一下如下的时间调整的输入控件
控件的代码如下,就是给一个 input 元素加了两个调整控件,可以用来调整输入的小时和分钟。
import { useEffect, useState } from "react";
function padLeadingZeros(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
function TimeInput({ hour, minute, onChange }) {
const [time, setTime] = useState("");
const [valuep, setValuep] = useState(0);
const setFormatTime = (hour, minute) => {
setTime(padLeadingZeros(hour, 2) + ":" + padLeadingZeros(minute, 2));
}
const handleAdd = () => {
let [hour_str, minute_str] = time.split(":");
let hour_i = parseInt(hour_str);
let minute_i = parseInt(minute_str);
if (valuep < 3) {
hour_i = hour_i + 1;
if (hour_i > 23) {
hour_i = 0;
}
} else {
minute_i = minute_i + 1;
if (minute_i > 59) {
minute_i = 0;
}
}
setFormatTime(hour_i, minute_i);
};
const handleMin = () => {
let [hour_str, minute_str] = time.split(":");
let hour_i = parseInt(hour_str);
let minute_i = parseInt(minute_str);
if (valuep < 3) {
hour_i = hour_i - 1;
if (hour_i < 0) {
hour_i = 23;
}
} else {
minute_i = minute_i - 1;
if (minute_i < 0) {
minute_i = 59;
}
}
setFormatTime(hour_i, minute_i);
};
const markCurrentPosition = (e) => {
setValuep(e.target.selectionStart);
}
useEffect(() => {
setFormatTime(hour, minute);
}, [hour, minute]);
return <>
<input type="text" value={time} onChange={onChange} onClick={markCurrentPosition} onKeyUp={markCurrentPosition} />
<div className="flex flex-col">
<div className="hover:bg-gray-200" onClick={handleAdd}>
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 cursor-pointer" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 15l7-7 7 7" />
</svg>
</div>
<div className="hover:bg-gray-200" onClick={handleMin}>
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 cursor-pointer" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</div>
</div>
</>
}
export { TimeInput }
然后在父元素中使用这个 TimeInput 组件:
import { TimeInput } from "../components/TimeInput";
const Parent = () => {
const [hour, setHour] = useState(0);
const [minute, setMinute] = useState(0);
const handleTimeInputChange = (e) => {
console.log("handleTimeInputChange", e.target.value);
};
return <>
<TimeInput hour={hour} minute={minute} onChange={handleTimeInputChange} />
</>
}
测试发现,控件的时间可以自由调整,问题是它的 onChange 事件回调 handleTimeInputChange
没有执行。我需要在这个 onChange 回调事件时获取控件输入的值。
谁能解释一下是什么原因吗?我感觉是我对 Reactjs 的数据流理解的不到位造成的。