如何从 on-change 事件中获取非字母数字键的值是 JS/React



当用户按回车键或转义键时无法引用。

我创建了一个计算器应用程序。 我希望按钮和键盘可用。 我的问题在于弄清楚如何引用输入键用法或转义键用法的值。 onChange 事件似乎没有给这些事件赋予价值?

我正在为此使用 React 中的类组件...

我被调用的函数是:

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的事件侦听器,当用户按下某个键时触发。您可以创建一个全新的事件处理程序,用于处理用户按转义键或回车键时的逻辑。

您只需要从事件中捕获键码,每个键都有相应的键码。

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事件同时使用。

我想通了! 我必须添加一个onKeyDown事件来引用userEntersNonNumber函数来引用输入键和转义键的值。 通过以下方式修复它:

<input className="screen" type="text" onChange={this.handleKeyboard} value={this.state.screenDisplay} **onKeyDown={this.userEntersNonNumber}**></input>

和:

userEntersNonNumber = (e) => {
let userInput = e.target.value;
**var x = e.key;**
console.log("Key pressed: ", x);
if (userInput.includes("+") === true) {
console.log('a plus sign was used');
this.addition();
} else if **(x === 'Enter')** {
console.log('the enter key was pressed');
this.solve();        
} else if **(x === 'Escape')** {
console.log('the escape key was pressed');
this.clearEntry();
} 

最新更新