无法读取未定义的属性“状态" [英] Cannot read property 'state' of undefined

查看:75
本文介绍了无法读取未定义的属性“状态"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从按钮单击中的输入中获取值,但是当我单击时出现错误:无法读取未定义的属性'state'

I'm trying to get the values ​​from the input in the button click but when I click the error appears: Cannot read property 'state' of undefined.

这是我的代码,在身份验证功能this.state中返回:无法读取未定义的属性"state".

This my code, in authentication function this.state returns: Cannot read property 'state' of undefined.

constructor(props) {
  super(props);
  this.state = {
    email: '',
    pass: ''
  }
}

handleChange (event) {
  this.setState({
    [event.target.name]: event.target.value
  })
}

authentication() {
 console.log(this.state);
}

render() {
        return (
            <Fragment>
                <LoginStyles />
                <main>
                    <section>
                        <h2 className="title">Login</h2>

                        <div className="form__login">
                            <label>Nome:</label>
                            <input type="text" name="email" onChange={event => this.handleChange(event)} />

                            <label>Senha:</label>
                            <input type="password" name="pass" onChange={event => this.handleChange(event)} />

                            <button className="btn-default" onClick={this.authentication}>Acessar</button>
                        </div>
                    </section>
                </main>
            </Fragment> 
        )
    }

推荐答案

您应该绑定身份验证功能和handleChange功能.为此,您可以在构造函数中使用bind方法,也可以如下使用ES6箭头运算符-

You should bind your authentication function as well as handleChange function. To do that you can either use bind method in constructor or use ES6 arrow operator as below-

handleChange = (event) => {
  this.setState({
    [event.target.name]: event.target.value
  })
}

authentication = () => {
 console.log(this.state);
}

这篇关于无法读取未定义的属性“状态"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆