gpt4 book ai didi

reactjs - 将 useRef 与 Array react 为动态

转载 作者:行者123 更新时间:2023-12-04 14:29:47 25 4
gpt4 key购买 nike

我试图让每个字母输入时焦点移动到下一个输入的组件。

我想我需要多个 ref像一个数组,但我不知道它。

这是问题的示例代码。

function PIN({length, onChange, value}){
const inputEl = React.useRef(null);
function handleChange(e){
onChange(e);
inputEl.current.focus();
}
return (
<div>
{
new Array(length).fill(0).map((i)=>(
<input type="text" ref={inputEl} onChange={handleChange} />
))
}
</div>
)
}

最佳答案

您可以创建多个引用

function PIN({length, onChange, value}){
const inputRefs = useMemo(() => Array(length).fill(0).map(i=> React.createRef()), []);
const handleChange = index => (e) => {
//onChange(e); // don't know about the logic of this onChange if you have multiple inputs
if (inputRefs[index + 1]) inputRefs[index + 1].current.focus();
}
return (
<div>
{
new Array(length).fill(0).map((inp, index)=>(
<input type="text" ref={inputRefs[index]} onChange={handleChange(index)} />
))
}
</div>
)
}

关于reactjs - 将 useRef 与 Array react 为动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61245376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com