简体   繁体   English

调用登录功能只需按“ enter”键一次

[英]To call login function Only once after pressing 'enter' key

I'm working on a login function right now. 我正在使用登录功能。 I put my enterKey function in the input, and my aim is to call the login function when the user press the enter key. 我将enterKey函数放入输入中,目的是在用户按下Enter键时调用登录函数。 It works fine if there's nothing in the input area, however, I find that if I have some characters in the input text area, the function will be called multiple times and give multiple error messages. 如果输入区域中没有任何内容,它可以正常工作,但是,我发现如果输入文本区域中有一些字符,该函数将被多次调用并给出多个错误消息。 For example, if I have N characters in the input, I will receive (N+1) error messages after press the enter key. 例如,如果我在输入中包含N个字符,则在按Enter键之后,我将收到(N + 1)条错误消息。 Here is my code: 这是我的代码:

 enterKeyPress() {
    window.addEventListener("keypress", e => {
      if (e.keyCode === 13) {
        console.log('enter key pressed!'); // I will receive this msg (N+1) times when there're N characters in the input text area 
        e.preventDefault();
        this.loginUser(); // this is the login function I want to call after press enter key, but just once per press
      }
    });
  }
 render() {
    return(
      <Input
         type="password"
         placeholder="Password"
         onChange={e =>
            this.setState({ password: e.target.value })
         }
         onKeyPress={this.enterKeyPress()}
      />
    );
}

Can anyone help me with this? 谁能帮我这个?

From some quick Googling, I think this might do what you need: 通过快速搜索,我认为这可以满足您的需求:

enterKeyPress(e) {
    if (e.keyCode === 13) {
      console.log('enter key pressed!'); // I will receive this msg (N+1) times when there're N characters in the input text area 
      e.preventDefault();
      this.loginUser(); // this is the login function I want to call after press enter key, but just once per press
    });
}
render() {
    return(
      <Input
         type="password"
         placeholder="Password"
         onChange={e =>
            this.setState({ password: e.target.value })
         }
         onKeyPress={this.enterKeyPress}
      />
    );
}

onKeyPress already does what the event listener you're trying to add does, so just pass it the keypress event directly instead. onKeyPress已经完成了您要添加的事件侦听器的操作,因此只需将其直接传递给keypress事件即可。

Like @Ronnie has pointed out in the comments, you are adding a new event listener every time the onKeyPress function is triggered on the component, which causes the problems. 就像@Ronnie在注释中指出的那样,每次在组件上触发onKeyPress函数时,您都会添加一个新的事件侦听器,这会导致问题。 Since onKeyPress event already passes the event as an argument (similar to onClick event), you can access the keyCode from there. 由于onKeyPress事件已经将event作为参数传递(类似于onClick事件),因此您可以从那里访问keyCode

You can change your enterKeyPress function to the following: 您可以将enterKeyPress函数更改为以下内容:

enterKeyPress(e) {
    if (e.keyCode === 13) {
      console.log('enter key pressed!'); 
      e.preventDefault();
      this.loginUser();
    }
  }

Event listeners aren't necessary in this case. 在这种情况下,事件监听器不是必需的。

First thing, adjust enterKeyPress to not create an event listener. 首先,调整enterKeyPress使其不创建事件侦听器。 If you haven't bound the function in your constructor, then you can convert enterKeyPress to an arrow function: 如果尚未在构造函数中绑定该函数,则可以将enterKeyPress转换为箭头函数:

enterKeyPress = (e) => {
    if (e.keyCode === 13) {
        console.log('enter key pressed!');
        e.preventDefault();
        this.loginUser();
    });
}

Converting enterKeyPress to an arrow function is one way to scope the function to the component. enterKeyPress转换为箭头函数是将函数范围enterKeyPress到组件的一种方法。 Another option is binding the function in your constructor or in your render function, which is well documented elsewhere. 另一种选择是将函数绑定到构造函数中或render函数中,这在其他地方已有详细记录。 If you've already bound the function in your constructor (you haven't included it here), then you can ignore that part. 如果已经在构造函数中绑定了该函数(此处未包括该函数),则可以忽略该部分。

Second, adjust your onKeyPress prop to pass the function rather than calling it: 其次,调整您的onKeyPress属性以传递函数,而不是调用它:

<Input
    type="password"
    placeholder="Password"
    onChange={e =>
        this.setState({ password: e.target.value })
    }
    onKeyPress={this.enterKeyPress}
/>

It's also worth noting that there's another general JavaScript mistake here: using an anonymous callback function in your event listener. 还值得注意的是,这里还有另一个通用的JavaScript错误:在事件监听器中使用匿名回调函数。 By using an anonymous function, you're enabling the same function to be added multiple times, since a different function reference is generated each time. 通过使用匿名函数,您可以多次添加同一函数,因为每次都会生成不同的函数引用。 This also means that you won't be able to remove it later, since you'll require the function reference to do so. 这也意味着您以后将无法删除它,因为您将需要函数引用来删除它。

Again, you don't need an event listener here, but if you did , you should probably define the callback in the component scope, so that you can remove it at some later point. 同样,您在这里不需要事件侦听器, 但是如果这样做了 ,您可能应该在组件范围内定义回调,以便以后可以将其删除。 A common pattern for using event listeners is as follows: 使用事件侦听器的常见模式如下:

handleKeyPress = (e) => {
    if (e.keyCode === 13) {
      console.log('enter key pressed!'); 
      e.preventDefault();
      this.loginUser();
    });
} 

componentDidMount() {
    window.addEventListener("keypress", this.handleKeyPress);
}

componentWillUnmount() {
    window.removeEventListener("keypress", this.handleKeyPress);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM