reactjs - 当我这样做时,它正在工作,但是当我以其他方式编写函数时,为什么它不起作用?
问题描述
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");}
解决方案
这是因为您不能const
在类中声明字段。
如果您删除const
,它将起作用。
goToDashboard = event => {
event.preventDefault();
console.log("I am Clicked");
};
CodeSandBox上的工作演示。
推荐阅读
- java - 如何避免在微调器选择后重置 UI?
- python - 如何测试所有变量的所有可能值以获得函数的最大结果
- c# - Newtonsoft 在 JArray 中添加键控 JObject
- c# - KeyValue 实践的通用类型约束不可比较
- javascript - componentDidUpdate 比 react-redux 落后两步
- json - Azure 资源组部署失败
- google-apps-script - 如何使用事件源电子表格从独立脚本在特定部署上创建可安装触发器?
- django - 从 django orm 中所有用户的最高分中查找平均分
- windows-services - 如何使用命令行在nssm中设置两个环境变量
- python - 如何使用模型管理器访问模板中的对象计数?