草庐IT

javascript - 按回车键时关注下一个字段 React.js

coder 2024-05-10 原文

当我使用 React.js 在输入中单击输入时,我想找到一种方法来关注下一个字段

  @autobind
  handleKeyPress(event){
    if(event.key === 'Enter'){
      this.refs.email.focus();
    }
  }

  @autobind
  handleKeyPressEmail(event){
    if(event.key === 'Enter'){
      this.refs.zip_code.focus();
    }
  }

        <input
          onKeyPress={this.handleKeyPress}
          ref = 'name'
        />

        <input
          onKeyPress={this.handleKeyPressEmail}
          ref = 'email'
        />

        <input
          ref = 'zip_code'
        />

这是迄今为止我找到的最好方法,但是我不想每次都创建一个函数来重复自己的想法。有没有更好更简洁的方法来实现它?

最佳答案

如果<form>存在:

function handleEnter(event) {
  if (event.keyCode === 13) {
    const form = event.target.form;
    const index = Array.prototype.indexOf.call(form, event.target);
    form.elements[index + 1].focus();
    event.preventDefault();
  }
}
...
<form>
  <input onKeyDown={handleEnter} />
  <input onKeyDown={handleEnter} />
  <input />
</form>

CodePen

没有<form> :

function useFocusNext() {
  const controls = useRef([]);

  const handler = (event) => {
    if (event.keyCode === 13) {
      // Required if the controls can be reordered
      controls.current = controls.current
        .filter((control) => document.body.contains(control))
        .sort((a, b) =>
          a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING
            ? -1 : 1
        );

      const index = controls.current.indexOf(event.target);
      const next = controls.current[index + 1];
      next && next.focus();

      // IE 9, 10
      event.preventDefault();
    }
  };

  return useCallback((element) => {
    if (element && !controls.current.includes(element)) {
      controls.current.push(element);
      element.addEventListener('keydown', handler);
    }
  }, []);
};

...
const focusNextRef = useFocusNext();

<input ref={focusNextRef} />
<input ref={focusNextRef} />
<button ref={focusNextRef}>Submit</button>

CodePen

关于javascript - 按回车键时关注下一个字段 React.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38577224/

有关javascript - 按回车键时关注下一个字段 React.js的更多相关文章

  1. javascript - 按回车键时关注下一个字段 React.js - 2

    当我使用React.js在输入中单击输入时,我想找到一种方法来关注下一个字段@autobindhandleKeyPress(event){if(event.key==='Enter'){this.refs.email.focus();}}@autobindhandleKeyPressEmail(event){if(event.key==='Enter'){this.refs.zip_code.focus();}}这是迄今为止我找到的最好方法,但是我不想每次都创建一个函数来重复自己的想法。有没有更好更简洁的方法来实现它? 最佳答案 如

随机推荐