首页 > 解决方案 > 如何在 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} />
));

标签: reactjs

解决方案


我已将选项卡索引添加到您的输入元素并使用它们在项目之间导航。

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>;

推荐阅读