使用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} />
));
我已将tab索引添加到您的输入元素,并使用它们在项目之间导航。
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}
/>
));
编辑:这是基于您的代码沙箱使用引用和演示的一种新方法。
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>;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句