【发布时间】:2020-02-04 23:21:43
【问题描述】:
看看下面的例子。我用一些捕鼠器功能增强了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>
)
}
}
我
【问题讨论】:
标签: javascript reactjs hotkeys input-field mousetrap