react受控与非受控输入

IT技术 reactjs
2021-05-27 12:47:42

我按照 React Form 教程创建了以下组件:

export default class SignInForm extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      email: '',
      password: ''
    }

    this.onEmailChange = this.onEmailChange.bind(this)
    this.onPasswordChange = this.onPasswordChange.bind(this)
  }

  onEmailChange(event) {
    this.setState({email: event.target.value})
  }

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

  render() {
    return (
      <form onSubmit={this.props.handleSubmit}>
        <div>
          <label>Email</label>
          <div>
            <input type="email"
              placeholder="you@gmail.com"
              onChange={this.onEmailChange}
              value={this.state.email}
            />
          </div>
        </div>
        <div>
          <label>Password</label>
          <div>
            <input type="password"
              placeholder="Password"
              onChange={this.onPasswordChange}
              value={this.state.password}
            />
          </div>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    )
  }
}

一旦表单呈现,我就会收到以下错误:

SignInForm 正在将密码类型的受控输入更改为不受控制。输入元素不应从受控切换到不受控制(反之亦然)。决定在组件的生命周期内使用受控或非受控输入元素

我找不到让它成为不受控制的组件的地方。我究竟做错了什么?

1个回答

看起来您的 onPasswordChange 方法应该是:

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