在表单输入字段上获取“对象可能为'null'。TS2531”

时间:2019-12-16 05:55:17

标签: javascript reactjs typescript firebase

我正在尝试构建一个简单的表单来捕获新用户在Firebase上注册的电子邮件和密码,正在使用带有Typescript的React,并且收到错误消息“对象可能为'null'。TS2531”在代码的以下部分:

 <form onSubmit={(event) => { this.handleSignUp({event, email: this._email.current.value, password: this._password.current.value})}}>

尤其是this._email.current.valuethis._password.current.value引发此错误。

我已经研究了错误代码和类型脚本,这与打字稿上的“ strictNullChecks”有关,但是我真的不想关闭该选项,而且我不认为我可以有足够的技巧或对编码的理解,以了解如何解决这个问题。尽管我确实知道可以使用空值提交表单,但稍后我将使用firebase auth进行检查,以确保存在长度超过4个字符的字符串。

下面是整个react组件的代码。

interface IHandleSubmitNewUserFunc {
    event: any,
    email: any,
    password: any
}

class NewUserSignup extends React.Component {
     constructor(props: any) {
         super(props);
         this.handleSignUp = this.handleSignUp.bind(this);
     }

    handleSignUp(input: IHandleSubmitNewUserFunc) {
        input.event.preventDefault();
        const { email, password } = input;
        if (email.length < 4 && email != null) {
            alert('Please enter an email address.');
            return;
        }
        if (password.length < 4 && password != null) {
            alert('Please enter a password.');
            return;
        }
        firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            if (errorCode == 'auth/weak-password') {
                alert('The password is too weak.');
            } else {
                alert(errorMessage);
            }
            console.log(error);
        });
    }

    private _email = React.createRef<HTMLInputElement>();
    private _password = React.createRef<HTMLInputElement>();

    render() {
        return <div>
            <div className="signup-modal-container">
                <div className="identity-panel">
                    <img src={logo}></img>
                    <form onSubmit={(event) => { this.handleSignUp({event, email: this._email.current.value, password: this._password.current.value})}}>
                        <div className="form-flex-container">
                            <div className="signup-item">
                                <h2>
                                    Sign Up
                                </h2>
                                <label htmlFor="email" id="email">
                                    Email:
                                </label>
                            </div>
                            <div className="signup-item">
                                <div className="input-container">
                                    <input type="text" name="email" id="email" ref={this._email}/>
                                </div>
                            </div>
                            <div className="signup-item">
                                <label htmlFor="password">
                                    Password:
                                </label>
                            </div>
                            <div className="signup-item">
                                <div className="input-container">
                                    <input type="password" name="password" id="password" ref={this._password}/>
                                </div>
                            </div>
                            <div className="signup-item">
                                <button type="submit">
                                    Sign Up
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <p>
            NewUserSignup is showing
            </p>

        </div>
    }
}
export default NewUserSignup;

我不确定是否要抛出此错误需要什么代码,不建议使用任何建议。

1 个答案:

答案 0 :(得分:1)

差不多。默认情况下,引用为null,因此无法保证current会在您访问它们时分配(据代码所知)。

您有2个选择:

  • 在访问this._email.currentthis._password.current之前添加真实检查。
const eCurrent = this._email.current;
const pCurrent = this._password.current;
if (!eCurrent || !pCurrent) {
  // This will probably never happen, to respond to events these will be hooked up.
  return;
}
  • 使用非null断言,因为您知道它是安全的操作:this._email.current!.value
// Assert that current won't be null.
const emailValue = this._email.current!.value;
const passwordValue = this._password.current!.value;