reactjs - 如何在 React 中实现输入自动选项卡(关注 keyup 事件的下一个输入元素)?
问题描述
使用 React 作为库,我有几个输入文本块,每个块的 maxlength=1,我想实现一个函数,每次在输入框中输入一个字符时,焦点都会转到下一个。
这是我正在谈论的输入元素列表:
这是 CodesSandbox 上的最小表示:https ://codesandbox.io/s/react-autotab-6kewb 。
如何在 React 中获得所需的行为?
这是相关的片段:
const autoTab = e => {
const BACKSPACE_KEY = 8;
const DELETE_KEY = 46;
if (e.keyCode === BACKSPACE_KEY) {
// TODO: implement backwards autoTab
} else if (e.keyCode !== DELETE_KEY) {
// TODO: implement forwards autoTab
}
};
const blocks = Array.from({ length: 10 }, (element, index) => (
<input className="block" key={index} maxLength={1} onKeyUp={autoTab} />
));
解决方案
我已将选项卡索引添加到您的输入元素并使用它们在项目之间导航。
const autoTab = e => {
const BACKSPACE_KEY = 8;
const DELETE_KEY = 46;
let tabindex = $(e.target).attr("tabindex") || 0;
tabindex = Number(tabindex);
if (e.keyCode === BACKSPACE_KEY) {
tabindex -= 1;
} else if (e.keyCode !== DELETE_KEY) {
tabindex += 1;
}
const elem = $("[tabindex=" + tabindex + "]");
if (elem[0]) {
elem.focus();
}
};
const blocks = Array.from({ length: 10 }, (element, index) => (
<input
className="block"
tabIndex={index}
key={index}
maxLength={1}
onKeyUp={autoTab}
/>
));
编辑:这是一种使用 refs 和基于您的代码沙箱的演示的新方法。
const autoTab = e => {
const BACKSPACE_KEY = 8;
const DELETE_KEY = 46;
let tabindex = $(e.target).attr("data-index") || 0;
tabindex = Number(tabindex);
let elem = null;
if (e.keyCode === BACKSPACE_KEY) {
elem = tabindex > 0 && elemRefs[tabindex - 1];
} else if (e.keyCode !== DELETE_KEY) {
elem = tabindex < elemRefs.length - 1 && elemRefs[tabindex + 1];
}
if (elem) {
elem.current.focus();
}
};
const Input = props => {
const ref = React.createRef();
elemRefs.push(ref);
return (
<input
className="block"
data-index={props.index}
ref={ref}
maxLength={1}
onKeyUp={props.autoTab}
/>
);
};
const blocks = Array.from({ length: 10 }, (element, index) => (
<Input key={index} index={index} autoTab={autoTab} />
));
const App = () => <div className="App">{blocks}</div>;
推荐阅读
- django - Django runserver 在启动期间抛出错误
- git - Jenkins 错误 - ssh:连接到主机端口 22:连接被拒绝
- perl - 如何使用 Perl(系统)使用包含元字符的参数执行外部程序“
- jwt - 为什么将 JWT 拆分为三个以点分隔的部分?
- excel - 如何在 Excel 中使用 VBA 向表中添加一行,其中第一列具有递增索引
- google-api - 如何从 Google Analytics 获取所有用户报告?
- matlab - 在 MatLab 中按标准加载文件
- java - 使用spring boot #SOAP Service调用多个并行调用SOAP服务
- node.js - Elasticsearch 映射、索引和查询自动完成输入短语
- apache-spark - Spark ar,如何创建拍摄效果