import { useRef, useState } from 'react'
function App() {
const [time, setTime] = useState(null);
const [running, setRunning] = useState(false);
const [editState, setEditState] = useState(false);
const [hms, setHms] = useState(Array(6).fill(0));
const inputs = useRef([]);
const handleChange = (e, idx) => {
const {value} = e.target;
if (value.match(/^\d$/)) {
const newHms = [...hms];
newHms[idx] = value;
setHms(newHms);
if (idx < 6) {
inputs.current[idx+1].focus();
}
if (value === '') {
if (idx > 0) {
inputs.current[idx - 1].focus();
}
}
}
}
const handleKeyDown = (e, idx) => {
if (e.key === 'Backspace') {
if (hms[idx] != '') {
const newHms = [...hms];
newHms[idx] = '';
setHms(newHms);
return;
}
if (idx > 0) {
inputs.current[idx - 1].focus();
}
}
}
return (
<>
<div id='root' style={{backgroundColor: "#e3b23c", width:"400px", height:"400px"}}>
{true && <div>
{
hms.map((_, idx) => {
return (
<span>
<input
key={idx}
type='text'
maxLength="1"
value={hms[idx]}
onKeyDown={(e) => handleKeyDown(e, idx)}
onChange={(e) => handleChange(e, idx)}
ref={(el) => (inputs.current[idx] = el)}
style={{width: '40px',
height: '40px',
margin: '0 5px',
textAlign: 'center',
fontSize: '18px',
border: '1px solid #ccc',
borderRadius: '4px'}
}
></input>
{(idx == 1 || idx == 3) && <span style={{
fontWeight: 600,
fontSize: "30px"
}}>:</span>}
</span>
);
})
}
</div>}
<div>
Hours : Minutes : Seconds
</div>
</div>
</>
)
}
export default App
onChange
处理程序移动到
onKeyDown
const handleChange = (e, idx) => {
};
const handleKeyDown = (e, idx) => {
const keyValue = e.key;
if (keyValue === "Backspace") {
if (hms[idx] != "") {
const newHms = [...hms];
newHms[idx] = "";
setHms(newHms);
return;
}
if (idx > 0) {
inputs.current[idx - 1].focus();
}
} else if (keyValue.match(/^\d$/)) {
const newHms = [...hms];
newHms[idx] = keyValue;
setHms(newHms);
if (idx < 5) {
inputs.current[idx + 1].focus();
}
}
};