reactjs onChange触发回调

时间:2015-09-02 15:14:44

标签: javascript reactjs

我正在尝试在reactJS中创建密码确认检查器。我目前正在测试在组件中触发回调。当我测试这个视图时,我看不到我的onChange触发任何回调。我对reactjs很新,所以我不确定为什么没有发生任何事情。

import React from 'react';

class SignUp extends React.Component {

    confirmPassword(event) {
        console.log("confirmPassword");
        console.log(event);
    }

    setInitialPassword(event) {
        console.log("setInitialPassword");
        console.log(event);
    }

    render() {
        return (
            <div>
                <form method="post" action="/signup">
                    <ul>
                        <li><input id="firstName" name="first_name" placeholder="First name" type="text" required="required" /></li>
                        <li><input id="lastName" name="last_name" placeholder="Last name" type="text" required="required" /></li>
                        <li><input id="email" name="email" placeholder="Email" type="email" required="required" /></li>
                        <li><input id="password" name="password" placeholder="Password" type="password" required="required" onChange={ this.setInitialPassword }/></li>
                        <li><input id="confirmPassword" name="confirm_password" placeholder="Confirm Password" type="password" required="required" onChange={ this.confirmPassword } /></li>
                        <span id="confirmMessage" class="confirm-message"></span>
                        <input type="submit" value="Sign up" />
                        <input type="reset" value="Cancel" />
                    </ul>
                </form>
            </div>
        );
    }
};

export default SignUp;

1 个答案:

答案 0 :(得分:1)

设置处理程序时需要绑定this

<li><input id="password" name="password" placeholder="Password" type="password" required="required" onChange={ this.setInitialPassword.bind(this) }/></li>
<li><input id="confirmPassword" name="confirm_password" placeholder="Confirm Password" type="password" required="required" onChange={ this.confirmPassword.bind(this) } /></li>

或使用ES6大箭头功能:

<li><input id="password" name="password" placeholder="Password" type="password" required="required" onChange={ e => this.setInitialPassword(e) }/></li>
<li><input id="confirmPassword" name="confirm_password" placeholder="Confirm Password" type="password" required="required" onChange={ e => this.confirmPassword(e) } /></li>