javascript - 如何从 onChange 事件中获取非字母数字键的值是 JS/React
问题描述
当用户按下回车键或退出键时无法引用。
我创建了一个计算器应用程序。我希望按钮和键盘可以使用。我的问题在于弄清楚如何引用输入键用法或转义键用法的值。onChange 事件似乎没有赋予那些价值?
为此,我在 React 中使用了一个类组件...
我调用 onChange 的函数是:
handleKeyboard = (e) => {
let userInput = e.target.value;
console.log("beginning of handleKeyboard fx: ", userInput);
this.setState({
screenDisplay: userInput
});
this.userEntersNonNumber(e);
}
然后,此函数访问以下函数以确定当用户输入非数字时要执行的操作....
userEntersNonNumber = (e) => {
let userInput = e.target.value;
if (userInput.includes("+") === true) {
console.log('a plus sign was used');
this.addition();
} else if (userInput.includes("-") === true) {
console.log('a minus sign was used');
this.subtraction();
} else if (userInput.includes("*") === true) {
console.log('a multiplication sign was used');
this.multiplication();
} else if (userInput.includes("/") === true) {
console.log('a division sign was used');
this.division();
} else if (userInput.includes("enter")) {
console.log('the enter key was pressed');
/* I have a function that does the math which would be referenced here */
} else if (userInput.includes("escape")) {
console.log('the enter key was pressed');
/* I have a function that clears the calculator which would be referenced
here */
} else {
console.log('keep typing')
}
}
调用函数的地方是:
screenDisplay 状态是一种显示用户迄今为止在计算器中输入的内容的方式。它是一个字符串,每输入一个键或按下按钮,该键/按钮的值就会被添加到字符串的末尾。
用户应该能够使用键盘上的回车键或退出键来调用求解或清除函数来计算他们的条目或清除计算器。按钮是可操作的,但击键不是。
解决方案
input
标签有另一个被调用的事件监听onKeyDown
器,当用户按下一个键时会触发它。您可以创建一个全新的事件处理程序来处理用户按下 Escape 或 Enter 键时的逻辑。
您只需要从事件中捕获keyCodes,每个键都有对应的keyCodes。
class App extends React.Component {
handleKeyDown = e => {
if (e.keyCode === 13) {
console.log("Enter action"); //replace with your code
} else if (e.keyCode === 27){
console.log("Escape action") //replace with your code
}
};
render() {
return <input onKeyDown={this.handleKeyDown} />;
}
}
您仍然可以在现有onChange
事件的同时使用此事件侦听器。
推荐阅读
- c# - How to convert 'GameObject to Custom Class'
- php - 如何使用 Get 函数作为对象
- visual-studio - 尝试从 Xamarin 表单中的列表视图中删除单元格/项目时,为列表视图的上下文操作获取红色背景
- apache-kafka - 为什么在 Kafka REST 代理中进行 base64 编码/解码?
- http - 无法在 if..else 条件中获取变量数据:“undefined err go”
- ssis - 在 CMD 中执行时,SSIS 包不移动文件
- mysql - 如何检查我的内部连接是对还是错?
- android - Android Google Map Gradle 依赖错误
- c++ - 矢量擦除循环给出错误,这是什么意思?
- jquery - 无法使用开放图在 Facebook 上分享动态图像