在 React 的另一个函数中调用一个函数

Calling a function inside another function in React

我正在制作一个可以正常工作的登录表单,我想要的是让按回车键与单击提交按钮一样。这是我的代码:

handleSubmit(e) {
      const TOKEN = 'Bearer ' + getToken();
        e.preventDefault();

        const datapost = {
          username : this.state.username,
          password : this.state.password

        }
        let axiosConfig = {
          headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            "Access-Control-Allow-Origin": "*",
            'Authorization': TOKEN
        }
        };
handleKeyDown(e){
        if (e.key === 'Enter') {
        console.log("working");
        this.handleSubmit(); 
        }
      } 

<TextField id="filled-basic" onKeyDown={this.handleKeyDown} label="Contrasenya" type="password" variant="filled" onChange={this.handleChange} name="password" value={this.state.password}/>

  <Button variant="contained" type="submit" onKeyDown={this.handleKeyDown} color="primary" size="small" onClick={this.handleSubmit} >

只需将 e.preventDefault(); 更改为 e && e.preventDefault();

或者,如果您可以使用最新的语言功能,那么您可以使用可选链接

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

e?.preventDefault();

正确的做法是不使用 keyDown 事件,而是使用表单。如果您用表单包围您的输入和提交按钮,您的 Enter 键按下将被自动视为提交。像这样:

<form onSubmit={this.handleSubmit}>
  <input type="text />
  <button type="submit">Submit</button>
</form>

不确定你的问题是什么,但如果你遇到错误,这可能会有所帮助

handleKeyDown(e){
    if (e.key === 'Enter') {
        console.log("working");
        this.handleSubmit(e); // <-- pass e next
    }
} 

如果你告诉我们更多的话,我可能会帮助你更多