如果两个表单字段匹配,则显示/隐藏按钮(密码确认)

问题描述 投票:0回答:1

伙计,我试图仅在两个表单字段匹配时显示Button。我在逻辑上缺少什么?当前行为是不可预测的,并且会随机显示按钮。

请原谅newb问题,很少的前端体验(如果没有的话)

谢谢!

class ResetPassword extends React.Component {
    constructor(props) {
         super(props);
         this.state = {};
         this.handleNewPasswordChange = this.handleNewPasswordChange.bind(this);
         this.handleConfirmPasswordChange = this.handleConfirmPasswordChange.bind(this);
         this.handleSubmit = this.handleSubmit.bind(this);
         this.checkPasswordMatch = this.checkPasswordMatch.bind(this);
    }

    handleNewPasswordChange(event) {
        this.setState({newPassword: event.target.value});
        this.checkPasswordMatch();
    }

    handleConfirmPasswordChange(event) {
        this.setState({confirmPassword: event.target.value});
        this.checkPasswordMatch();
    }

    checkPasswordMatch() {
        if (this.state.newPassword === this.state.confirmPassword && this.state.newPassword.length > 4) {
            this.setState({passwordsMatch: true});
        } else {
            this.setState({passwordsMatch: false});
        }
        this.forceUpdate();
    }

    render() {
        return (
            <Container>
                <h1>
                    Password Reset
                </h1>
                <div className="login-box">
                    <form onSubmit={this.handleSubmit}>
                        <label>
                            {strings.NewPassword} : &nbsp;
                            <input
                                id="newPassword"
                                name="newPassword"
                                type="password"
                                value={this.state.newPassword}
                                onChange={this.handleNewPasswordChange} />
                        </label>
                        <label>
                            {strings.ConfirmPassword} : &nbsp;
                            <input
                                id="confirmPassword"
                                name="confirmPassword"
                                type="password"
                                value={this.state.confirmPassword}
                                onChange={this.handleConfirmPasswordChange} />
                        </label>
                        { this.state.passwordsMatch ? <Button>{strings.ChangePassword}</Button> : null }
                    </form>
                </div>
            </Container>
        )
    }
}
reactjs
1个回答
0
投票

从下面的功能中删除this.forceUpdate();。这不是必需的,因为状态更改已经触发了重新渲染。

[this.forceUpdate();甚至在您的状态实际更新之前就运行,因为setState()的异步行为会导致意外的行为。

checkPasswordMatch() {
        if (this.state.newPassword === this.state.confirmPassword && this.state.newPassword.length > 4) {
            this.setState({passwordsMatch: true});
        } else {
            this.setState({passwordsMatch: false});
        }
        this.forceUpdate();
    }
© www.soinside.com 2019 - 2024. All rights reserved.