简体   繁体   English

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

[英]How to test if two inputs are the same in react during on onChange event?

I am trying to do an onChange event in react and test if two input fields are the same. 我正在尝试在onChange中做一个onChange事件,并测试两个输入字段是否相同。 This is for confirming a password. 这是用于确认密码。 I want to show a little message below as they are typing if the passwords match or do not match. 如果密码匹配或不匹配,我想在下面输入一些小信息。 I tried to set that state and compare the state in the onChange event, but that did not work because I would get the state 1 step behind. 我尝试设置该状态并在onChange事件中比较该状态,但这没有用,因为我将状态落后了1步。

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;

Note: I tried to solve this problem as I understood your requirement. 注意:由于我了解您的要求,因此我尝试解决此问题。 Note:check out following example, and let me know if it helps. 注意:请查看以下示例,让我知道是否有帮助。

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>
    );
}

} }

In my opinion the best way is 我认为最好的方法是

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
    }
  }));
}

Why best option. 为什么是最佳选择。
First less alteration to your existing code. 首先,减少对现有代码的更改。
Second you are resetting state once(you need keep updating state as less as possible). 第二,您一次重置状态(您需要保持尽可能少的更新状态)。
And last you need to keep values from event, because if event updates while setState callback finishes execution, you will have another event. 最后,您需要保留事件中的值,因为如果在setState回调完成执行过程中事件更新,则将有另一个事件。 So better keep all required values assigned to variable. 因此最好将所有必需的值分配给变量。

I remember using ref sometime ago in an old react project and that seemed to do the trick. 我记得以前在一个旧的react项目中使用ref,这似乎可以解决问题。 I think ref is react only, but not positive. 我认为ref仅是反应,而不是积极的。 Anyway, 无论如何,

Use ref and set it to a this value in the input like so: 使用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)} />

In the onChange function I called this and compared the two doing this: 在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
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM