簡體   English   中英

無法在React項目中讀取未定義的屬性“值”?

[英]Cannot read property 'value' of undefined in react project?

我嘗試使用react js和firebase創建一個Login。 當我嘗試編譯它時,它給出如下錯誤

TypeError: Cannot read property 'value' of undefined

我試圖在控制台中顯示用戶輸入。

我的Login.jsx文件如下所示

import React, { Component } from 'react';

class Login extends Component {

    constructor(props){
        super(props);
        this.authWithEmailPassword = this.authWithEmailPassword.bind(this);
    }

    authWithEmailPassword(event) {
        event.preventDefault();
        console.log("authed with email");
        console.table([{
            email: this.emailInput.value,
            password: this.passwordInput.value
        }])
    }

    render(){
        return(
            <div style={loginStyle}>
                <hr style={{marginTop: "10px", marginBottom: "10px"}} />
                <form onSubmit={(event)=> {this.authWithEmailPassword(event) }}
                ref={(form) => { this.loginForm = form }}>
                    <div style={{ marginBottom: "10px" }} className="pt-callout pt-icon-info-sign">
                        <h5>Note</h5>
                        If you dont have an account, this form will create your account 
                    </div>
                    <label className="pt-label">
                        Email
                        <input style={{width: "100%"}} className="pt-input" name="email" type="email"
                        ref="{(input) => {this.emailInput=input}}" placeholder="Email"/>
                    </label>

                    <label className="pt-label">
                        Password
                        <input style={{width: "100%"}} className="pt-input" name="password" type="password"
                        ref="{(input) => {this.passwordInput=input}}" placeholder="Password"/>
                    </label>
                    <input type="submit" style={{width: "100%"}} className="pt-button pt-intent-primary" value="Login"/>
                </form>
            </div>
        );
    }
}

export default Login;

我做錯了什么事,請幫助我。我還是新手。 我怎樣才能解決這個問題

刪除ref變量中的雙引號。 它應該是

ref={(input) => {this.passwordInput = input}}

更改您的裁判ref={(input) => this.emailInput = input}

ref={(input) => this.passwordInput = input}

下面是帶有您的代碼的演示代碼

用你的代碼演示

為了獲得更好的用例,請在ref上使用state或props來獲取表單數據

參考: 使用狀態或refs-react-js-form-components

改變你的代碼

<input style={{width: "100%"}} className="pt-input" name="email" type="email"ref="{(input) => this.emailInput=input}" placeholder="Email"/>

<input style={{width: "100%"}} className="pt-input" name="password" type="password" ref="{(input) => this.passwordInput=input}" placeholder="Password"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM