回答 - 如何覆盖输入框内部的当前字符(OTP输入)已满?

问题描述 投票:0回答:1

目前在输入框内(0),但由于它已经填充,我无法覆盖IT

代码沙盒示例

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
javascript reactjs jsx
1个回答
0
投票
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(); } } };

	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.