reactjs - 将 useRef 与 Array 反应以实现动态
问题描述
我正在尝试使每个字母输入时焦点移动到下一个输入的组件。
我想我需要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>
)
}
推荐阅读
- sql - 如何从同一张表中的另一条记录中获取价值?
- regex - 正则表达式前瞻量词
- python - 将文本文件导入python并将每个字符分隔到表python中的一个单元格中
- javascript - php文件内的内联javascript中的Vscode实验性装饰器警告
- python - Netmiko SecureCopy 进度条
- c# - 画布 C# 中的 dxf 文件
- sql - spark中变量生成的问题
- c# - 创建一对多和多对一关系 - SQLite & Entity Framework
- php - PHP中的PDO删除查询不生效
- php - 无法验证来自数据库 symfony 4 的用户重定向到相同的登录页面