无法读取反应项目中未定义的属性“值”?

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

我尝试使用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;

我做错了什么请帮助我这件事我还是个新手。我怎样才能解决这个问题

javascript reactjs firebase
3个回答
0
投票

删除ref变量中的双引号。它应该是

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


0
投票

用这个改变你的代码

<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"/>

0
投票

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

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

下面是您的代码的演示代码

demo with your code

对于更好的用例,请使用state或props over ref来获取表单数据

参考:use-state-or-refs-in-react-js-form-components

© www.soinside.com 2019 - 2024. All rights reserved.