簡體   English   中英

按 Enter React.js 時專注於下一個字段

[英]Focus on next field when pressing enter React.js

當我使用 React.js 在輸入中單擊 Enter 時,我想找到一種專注於下一個字段的方法

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

代碼筆

沒有<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>

代碼筆

您可以通過 for-in 循環使用 componentDidMount 和自動綁定引用。

http://codepen.io/jzmmm/pen/PzZgRX?editors=0010

  constructor() {
    super();
    this._handleKeyPress = this._handleKeyPress.bind(this);
  }

  // Loop through the ref's object, and bind each of them to onkeypress
  componentDidMount() {
    for (let x in this.refs) {
      this.refs[x].onkeypress = (e) => 
        this._handleKeyPress(e, this.refs[x]);
    }
  }

  // This checks ENTER key (13), then checks if next node is an INPUT
  // Then focuses next input box
  _handleKeyPress(e, field) {
    if (e.keyCode === 13) {
      e.preventDefault(); // Prevent form submission if button present
      let next = this.refs[field.name].nextSibling;

      if (next && next.tagName === "INPUT") {
        this.refs[field.name].nextSibling.focus();
      }
    }
  }

  render() {
    return (
        <form>
          <input type="text" name="name" ref='name' />
          <input type="text" name="email" ref='email' />
          <input type="text" name="zip_code" ref='zip_code' />
        </form>
    );
  }

這就是我設法使它更簡單的方法:

  @autobind
  handleKeyPress(value, event){
    if(event.key === 'Enter'){
      this.refs[event].focus();
    }
  }

    <input
      onKeyPress={(event) => this.handleKeyPress('email', event)}
      ref = 'name'
    />

    <input
      onKeyPress={(event) => this.handleKeyPress('zip_code', event)}
      ref = 'email'
    />

    <input
      ref = 'zip_code'
    />

沒有<form>和 TypeScript 版本。 跳過禁用的輸入。

const onKeyPress: React.KeyboardEventHandler<HTMLInputElement> = useCallback(
  (e) => {
    if (e.key === "Enter") {
      const inputs = Array.from(
        // Get table or tbody whatever that contains all inputs. The number of parentElements depends on the structure of your html
        e.currentTarget?.parentElement?.parentElement?.parentElement?.querySelectorAll(
          "input"
        ) ?? []
      ).filter((e) => !e.disabled)
      const index = inputs.indexOf(e.currentTarget)
      inputs[index + 1]?.focus()
      e.preventDefault()
    }
  },
  []
)

return <input type="number" onKeyPress={onKeyPress} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM