使用 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} />
));
Run Code Online (Sandbox Code Playgroud)
我已将选项卡索引添加到您的输入元素并使用它们在项目之间导航。
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}
/>
));
Run Code Online (Sandbox Code Playgroud)
编辑:这是基于您的代码沙箱使用 refs 和Demo的新方法。
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>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4948 次 |
| 最近记录: |