使用 Mousetrap.js 聚焦输入字段 - 但输入字段也将热键粘贴为值?

Focusing input field with Mousetrap.js - but input field also pastes the hotkey as value?

看看下面的例子。我用一些捕鼠器功能增强了 the official example here。因此,每当有人按下 alt+1 时,第一个输入字段将获得焦点,每当有人按下 alt+2 时,第二个输入字段将获得焦点。有用。

问题: 但是,输入字段然后也将按下的任何值作为热键(alt+1 然后呈现为 ​​¡alt+2 呈现为输入中的 但我只希望它是一个热键,我不希望它是输入字段中的实际值。我该怎么做呢?

我可以完全清除/删除输入字段。这在此处的示例中可行,但我不想这样做,因为在我的最终应用程序中需要保留输入字段的状态,所以我不能只删除它。

有什么建议吗?

import React from "react"
import Mousetrap from "mousetrap"

export default class CustomTextInput extends React.Component {
  constructor(props) {
    super(props)
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef()
    this.textInput2 = React.createRef()
    this.focusTextInput = this.focusTextInput.bind(this)
  }

  componentDidMount() {
    Mousetrap.bind("alt+1", () => {
      this.focusTextInput(1)
    })

    Mousetrap.bind("alt+2", () => {
      this.focusTextInput(2)
    })
  }

  focusTextInput(id) {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    if (id === 1) {
      this.textInput.current.focus()
    }
    if (id === 2) {
      this.textInput2.current.focus()
    }
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input type="text" ref={this.textInput} className="mousetrap" />
        <input type="text" ref={this.textInput2} className="mousetrap" />
      </div>
    )
  }
}

你试过 event.preventDefault() 了吗?

Mousetrap.bind("alt+1", (e) => {
            e.preventDefault();
      this.focusTextInput(1);
    })

    Mousetrap.bind("alt+2", () => {
        e.preventDefault();
    this.focusTextInput(2)
    })