这个问题在这里已经有一个答案:>
Unable to access React instance (this) inside event handler5个
我收到这个错误Uncaught TypeError:当我在AuthorForm的输入框中输入任何内容时,不能读取未定义的属性’state’.我正在使用React与ES7.
我收到这个错误Uncaught TypeError:当我在AuthorForm的输入框中输入任何内容时,不能读取未定义的属性’state’.我正在使用React与ES7.
该错误发生在ManageAuthorPage中setAuthorState函数的第3行.不管这行代码,即使我在setAuthorState中放置了console.log(this.state.author),它将在console.log中停止并调出错误.
在互联网上找不到类似的问题.
这是ManageAuthorPage代码:
import React,{ Component } from 'react'; import AuthorForm from './authorForm'; class ManageAuthorPage extends Component { state = { author: { id: '',firstName: '',lastName: '' } }; setAuthorState(event) { let field = event.target.name; let value = event.target.value; this.state.author[field] = value; return this.setState({author: this.state.author}); }; render() { return ( <AuthorForm author={this.state.author} onChange={this.setAuthorState} /> ); } } export default ManageAuthorPage
这里是AuthorForm代码:
import React,{ Component } from 'react'; class AuthorForm extends Component { render() { return ( <form> <h1>Manage Author</h1> <label htmlFor="firstName">First Name</label> <input type="text" name="firstName" className="form-control" placeholder="First Name" ref="firstName" onChange={this.props.onChange} value={this.props.author.firstName} /> <br /> <label htmlFor="lastName">Last Name</label> <input type="text" name="lastName" className="form-control" placeholder="Last Name" ref="lastName" onChange={this.props.onChange} value={this.props.author.lastName} /> <input type="submit" value="Save" className="btn btn-default" /> </form> ); } } export default AuthorForm
解决方法
您必须将事件处理程序绑定到正确的上下文(这):
onChange={this.setAuthorState.bind(this)}