首页 > 解决方案 > 如何从 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 状态是一种显示用户迄今为止在计算器中输入的内容的方式。它是一个字符串,每输入一个键或按下按钮,该键/按钮的值就会被添加到字符串的末尾。

用户应该能够使用键盘上的回车键或退出键来调用求解或清除函数来计算他们的条目或清除计算器。按钮是可操作的,但击键不是。

标签: javascriptreactjsevents

解决方案


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事件的同时使用此事件侦听器。


推荐阅读