Я пытаюсь создать окно ввода для ввода в стиле таймера/OTP. Полный? Придется вручную отступить и удалить символ, а затем вы можете пополнить ...
В настоящее время внутреннее входное поле (0), но, поскольку он уже заполнен, я не могу перезаписать его
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 (
{true &&
{
hms.map((_, idx) => {
return (
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'}
}
>
{(idx == 1 || idx == 3) && :}
);
})
}
}
Hours : Minutes : Seconds
)
}
export default App
Подробнее здесь: https://stackoverflow.com/questions/794 ... nputs-when