React Controlled与Uncontrolled输入

时间:2016-04-13 01:13:59

标签: reactjs

我按照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 个答案:

答案 0 :(得分:7)

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

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