无法读取 ReactJS 中未定义的属性“状态”(Gatsby)

Ron*_*rel 0 javascript event-handling reactjs gatsby

我有以下代码:

export default class Contact extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        password: '',
        redirect: false,
        username: ''
      };

  this.onUsernameChange = this.onUsernameChange.bind(this);
  this.onPasswordChange = this.onPasswordChange.bind(this);
}

onUsernameChange(event) {
  this.setState({ username: event.target.value });
}

onPasswordChange(event) {
  this.setState({ password: event.target.value });
}

handleSubmit(event) { 
  event.preventDefault();
  alert('A name was submitted: ' + this.state.username);

  //sessionStorage.setItem('username', this.state.username);

}

render() {

  return (
      <div>
        <form className="form-signin" onSubmit={this.handleSubmit}>
          <input type="text" value={this.username} onChange={this.onUsernameChange} />
          <input type="password" value={this.password} onChange={this.onPasswordChange} />
          <input type="submit" value="Submit" />
        </form>
      </div>
  );
}
}
Run Code Online (Sandbox Code Playgroud)

提交用户名和密码后:出现以下错误:

TypeError: Cannot read property 'state' of undefined
Run Code Online (Sandbox Code Playgroud)

在以下行:

alert('A name was submitted: ' + this.state.username);
Run Code Online (Sandbox Code Playgroud)

问题是什么?用户名不保存?(我正在使用 gatsby-reactjs)

Ana*_*via 5

你忘了绑定handleSubmit,以及

做:

this.onUsernameChange = this.onUsernameChange.bind(this);
this.onPasswordChange = this.onPasswordChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
Run Code Online (Sandbox Code Playgroud)

在构造函数中


Ans*_*sal 5

您还可以对函数使用 es6 格式,这样可以避免每次在构造函数中编写额外的代码来绑定 this 上下文。例如。

onUsernameChange = event => {
  this.setState({ username: event.target.value });
}
Run Code Online (Sandbox Code Playgroud)