javascript - 警报给出 TypeError:这是未定义的
问题描述
我正在制作一个反应应用程序create-app
,我正在制作一个注册表格,它现在只有两个字段,一个用于电子邮件,一个用于密码。
我正在做一个简单的测试,我想通过使用警报来显示我输入的值,就像这样:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
email:'',
password:''
};
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
handleEmailChange(e){
this.setState({email:e.target.value})
}
handlePasswordChange(e){
this.setState({password:e.target.value})
}
signIn(){
alert('Email address is ' + this.state.email + ' Password is ' + this.state.password);
}
render() {
return (
<form className="form-signin">
<h2 className="form-signin-heading"> Please sign in </h2>
<label for="inputEmail" className="sr-only"> Email address</label>
<input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required autofocus />
<label for="inputPassword" className="sr-only"> Password</label>
<input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />
<button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button"> Sign in </button>
</form>
);
}
}
export default App;
当我跑
npm start
我可以在 localhost 上看到我的应用程序,但是当我填写值并希望查看这些结果时,我收到此错误:
TypeError: this is undefined
23 | signIn(){
> 24 | alert('Email address is ' + this.state.email + ' Password is ' + this.state.password);
25 | }
我怎样才能修复这个错误?
解决方案
您需要在构造函数中绑定它,就像使用其他函数一样。在构造函数中添加:
this.signIn= this.signIn.bind(this);
推荐阅读
- javascript - 当我运行 node js 时,我收到一个错误: SyntaxError: Unexpected token '<'
- angularjs - 角轨道通过给出缺失属性错误
- css - 反应 CSS 主题
- ios - 从 `navigationBar.backBarButtonItem` 中删除 `UIMenu`
- visual-studio-code - Cypress / Visual Studio Code / Cypress 无法启动
- javascript - 在我的 React JS 示例中,Array.from(object) 不会将对象转换为数组
- python - 为什么相同算法的执行时间在 numpy 的模块中编码时会发生如此大的变化
- python - PutItem AWS DynamoDB 的无效类型错误
- c++ - 程序输出不再出现在集成终端中
- spring-boot - 使用 Querydsl 和 Spring Boot 进行 GroupBy 查询