首页 > 解决方案 > 当我这样做时,它正在工作,但是当我以其他方式编写函数时,为什么它不起作用?

问题描述

    import React from 'react';

    class Login extends React.Component {
       goToDashboard(event){
         event.preventDefault();
         console.log("I am Clicked");}

    render() {
    return(
      <div>
        <h2>Login</h2>
        <form onSubmit={this.goToDashboard}>
          <label>FirstName</label>
          <input type="text" placeholder="Email" name="email" /><br />
          <label>Password</label>
          <input type="password" placeholder="password" name="password" /><br />
          <button type="submit">Login</button>
        </form>
      </div>
    )
  }
}
export default Login;

当我按照我在上面声明的方式编写函数时,一切正常,但是当我使用箭头函数而不是它时,它显示错误,为什么?

       const goToDashboard = (event) => {
         event.preventDefault();
         console.log("I am Clicked");}

标签: reactjs

解决方案


这是因为您不能const在类中声明字段。
如果您删除const,它将起作用。

  goToDashboard = event => {
    event.preventDefault();
    console.log("I am Clicked");
  };

CodeSandBox上的工作演示。


推荐阅读