如何在onChange事件期间测试两个输入是否相同?

时间:2018-01-15 19:49:37

标签: javascript reactjs

如果两个输入字段相同,我正在尝试在反应和测试中执行onChange事件。这是用于确认密码。如果密码匹配或不匹配,我想在下面显示一条消息。我试图设置该状态并比较onChange事件中的状态,但这不起作用,因为我会让状态落后一步。

import React, { Component } from 'react';
import swal from 'sweetalert';

class UpdateUserPasswordTest extends Component {
  constructor(props) {
    super(props);

    this.state = {
      user: {
        currentPass: '',
        newPass: '',
        confirmNewPass: ''
      },
      match: false
    };

    this.updatePassword = this.updatePassword.bind(this);
    this.submitUserPassword = this.submitUserPassword.bind(this);
  }

  updatePassword(event) {
    event.preventDefault();

    this.setState({
      user: {
        ...this.state.user,
        [event.target.name]: event.target.value
      }
    });

    if (this.state.user.newPass === this.state.user.confirmNewPass) {
      this.setState({
        match: true
      });
    }
  }

  submitUserPassword() {
    this.props.onUpdatePassword(this.state.user);
  }

  render() {
    const { currentPass, newPass, confirmNewPass } = this.state.user;
    return (
      <div>
        <input
          type="password"
          name="currentPass"
          placeholder="Current Password"
          onChange={e => this.updatePassword(e)}
          value={currentPass}
        />
        <input
          type="password"
          name="newPass"
          placeholder="New Password"
          onChange={e => this.updatePassword(e)}
          value={newPass}
        />
        <input
          type="password"
          name="confirmNewPass"
          placeholder="Confirm New Password"
          onChange={e => this.updatePassword(e)}
          value={confirmNewPass}
        />
        <button onClick={this.submitUserPassword}>Update Pasword</button>
        {this.state.match === false ? (
          <div style={{ color: 'red' }}>Passwords Must Match</div>
        ) : (
          <div style={{ color: 'green' }}>Passwords Match!</div>
        )}
      </div>
    );
  }
}

export default UpdateUserPasswordTest;

3 个答案:

答案 0 :(得分:1)

注意:我试图解决这个问题,因为我理解你的要求。 注意:请查看以下示例,如果有帮助请告诉我。

class UpdateUserPasswordTest extends Component {
    constructor(props) {
        super(props);

        this.state = 
        {
        currentPass:null,
        newPass:null,
        confirmNewPass:null,
        checkMessage: null
         };

    this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit() {
    if(this.newPass == this.confirmNewPass) {
        this.setState({checkMessage: "Your password have changed."});
    } else {
        this.setState({checkMessage: "Some error occured during password change."});
    }
}

render() {
    return (
        <div>
            <div>
                Old Password:<input type="password" name="currentPass" placeholder="Current Password" onChange={this.handleCurrentPass} value={this.state.currentPass} />
                <br />
                New Password:<input type="password" name="newPass" placeholder="New Password" onChange={this.handleNewPass} value={this.state.newPass}/>
                <br />
                Rewrite New Password:<input type="password" name="confirmNewPass" placeholder="Confirm New Password" onChange={this.handleConfirmNewPass} value={this.state.confirmNewPass}/>
                <br />
                <button onClick={this.handleSubmit}>Update Pasword</button>
            </div>
            <div>{this.state.checkMessage}</div>
        </div>
    );
}

}

答案 1 :(得分:1)

在我看来,最好的方法是

updatePassword(event) {
  event.preventDefault();
  const {name, value} = event.target

  const isNewPass = name === 'newPass' && value;

  this.setState(({currentPass}) => ({
    user: {
      ...this.state.user,
      [name]: value,
      match: isNewPass && value === currentPass
    }
  }));
}

为什么选择最好的选择 首先减少对现有代码的更改。
其次,您要重置状态一次(您需要尽可能少地更新状态) 最后你需要保留事件中的值,因为如果在setState回调完成执行时事件更新,你将有另一个事件。因此,最好将所有必需值分配给变量。

答案 2 :(得分:0)

我记得前一段时间在一个旧的反应项目中使用ref,这似乎可以解决问题。我认为ref只是反应,但不是积极的。无论如何,

使用ref并将其设置为输入中的this值,如下所示:

<input type="text" ref={input => { this.firstInput = input }} onChange={e => this.comparePassword(e)} />

<input type="text" ref={input => { this.secondInput = input }} onChange={e => this.comparePassword(e)} />

在onChange函数中我调用了这个并比较了两个这样做:

comparePassword(event){
 event.preventDefault(); //incase you want to prevent certain things from happening

 if(this.firstInput.value === this.secondInput.value){
  //Code for passwords being equal goes here
 }
}