Reactjs 在onKeyDown之前,在更改时对输入作出反应

Reactjs 在onKeyDown之前,在更改时对输入作出反应,reactjs,react-hooks,Reactjs,React Hooks,const{usemo,useState,createRef}=React; 常量InputPIN=(道具)=>{ constinputrefs=useMemo(()=>Array(4).fill(0).map(i=>createRef()),[]); const[values,setValues]=useState(数组(4).fill(“”)); 函数句柄更改(e,索引){ const typed=e.target.value.toString(); 设置值((上一个)=> 上一地图((i,

const{usemo,useState,createRef}=React;
常量InputPIN=(道具)=>{
constinputrefs=useMemo(()=>Array(4).fill(0).map(i=>createRef()),[]);
const[values,setValues]=useState(数组(4).fill(“”));
函数句柄更改(e,索引){
const typed=e.target.value.toString();
设置值((上一个)=>
上一地图((i,jndex)=>{
if(index==jndex)返回类型化的[typed.length-1];
否则我会回来;
})
);
如果(键入!=''&&inputRefs[index+1])inputRefs[index+1].current.focus();
}
功能把手靠背空间(e,索引){
如果(如keyCode===8){
if(inputRefs[index-1]){
inputRefs[index-1].current.focus();
}
}
}
返回(
{
新数组(4).填充(0).映射((i,索引)=>(
handleBackspace(e,index)}type=“text”ref={inputRefs[index]}onChange={(e)=>handleChange(e,index)}/>)
}
)
}
常量应用=()=>{
返回(
)
}
ReactDOM.render(,document.getElementById('root'))

编辑:在评论中讨论后,整个答案已更新

我认为您可以使用一个自定义处理程序函数,并稍微重写两个处理程序方法:

const manualUpdateInputs = (index) => {    
    const newValues = [...values];

    newValues[index] = '';
    inputRefs[index].current.focus();    
}

const handleChange = (e, index) => {
    const newValues = [...values];
    const typed = e.target.value.toString();

    newValues[index] = typed;

    if (typed !=='' &&  inputRefs[index + 1]) {
       inputRefs[index + 1].current.focus();
    }

    setValues(newValues);
}

const handleBackspace = (e, index) => {
    if(e.keyCode === 8){
        if(inputRefs[index-1] && e.target.value === '') {
            manualUpdateInputs(index - 1);
        }
    }
}
我已经改变了你更新
值的方式
,但是你可以保持你的方式,它不会改变。重要的是使用
manualUpdateInputs

“诀窍”是,只要你点击键盘上的一个键,
handleBackspace
就会被触发,但是如果你点击了一个空白
的退格,就不会触发
handleChange


告诉我使用此实现获得的行为是否是您想要的(这对我来说很有意义,但可能不是您想要的)。

onChange()
没有给出
e.keyCode
我的错误,我很抱歉。我将编辑我的答案,寻找解决方案,但首先是一个问题,因为通过查看您的代码片段,我不确定您想要什么。想象一下,我已经填充了第一个
,现在我将注意力集中在第二个
上。如果我按backspace键,我应该只改变前一个
上的焦点,还是同时删除第一个
中的字符?然后,如果我将焦点放在已经填充的第二个
,然后按backspace,我应该删除该值并将焦点放在前一个
上还是仅仅删除该值?在我的代码段上,我有4个输入,我可以键入它们。如果我输入完所有输入,并且输入了
backspace
,则会出现问题。很抱歉,我迟到了。我已经通过使用ref实现了您想要的(我将在答案中解释选择)。不过,现在的行为并不好:如果我填充了所有输入,然后退格,我删除了最后一个输入,并将焦点更改为上一个
,但是我将焦点放在已经填充的
上,如果我输入一个数字,它将被输入到已经填充的
中。我不知道这是否是你想要的。我已经更新了答案,看看新代码:)