【发布时间】:2020-01-21 21:03:48
【问题描述】:
我在 if 语句中有一个 this 值,嵌套在我的 handleFormChange 函数中。我尝试使用带有此函数的箭头函数来绑定 this 的值,但我收到以下错误消息:
TypeError: Cannot set property 'author' of undefined
据我了解,通常您可以通过查看包含this 的函数的调用位置来找到this 的值。但是,就我而言,我正在努力解决这个问题。谁能向我解释为什么它是未定义的以及如何解决这个问题?代码如下:
class CommentForm extends React.Component{
constructor(props){
super(props)
var comment={author:'', message:''}
}
handleSubmit= (e)=>{
e.preventDefault()
var authorVal = this.comment.author;
var textVal = this.comment.message;
//this stops any comment submittal if anything missing
if (!textVal || !authorVal) {
return;
}
this.props.onCommentSubmit(this.comment);
//reset form values
e.target[0].value = '';
e.target[1].value = '';
return;
}
handleFormChange= (e)=>{
e.preventDefault()
if(e.target.name==='author'){
var author = e.target.value.trim();
this.comment.author = author
}else if(e.target.name==='message'){
var message = e.target.value.trim();
this.comment.message = message
}
}
render() {
return (
<form className = "ui form" method="post" onChange={(e)=>{this.handleFormChange(e)}} onSubmit={(e)=>{this.handleSubmit(e)}}>
<div className="form-group">
<input
className="form-control"
placeholder="user..."
name="author"
type="text"
/>
</div>
<div className="form-group">
<textarea
className="form-control"
placeholder="comment..."
name="message"
/>
</div>
<div className="form-group">
<button disabled={null} className="btn btn-primary">
Comment ➤
</button>
</div>
</form>
);
}
}
export default CommentForm
【问题讨论】:
-
var 注释
-
你从来没有在
this中发表评论。this.comment = {author:'', message:''} -
不是说
this未定义,而是说this.comment未定义。 -
有人能解释一下为什么在声明变量时需要使用
this吗?以前我从未在构造函数中使用this声明变量,除非它是状态 -
this指的是类实例范围,但是如果您在其中声明一个变量,它将仅在该块范围(构造函数)上可用,因此如果您想从另一个块中检索它,它不会在那里。this范围在该类实例的所有块中都可用。您应该阅读有关面向对象编程的更多信息。
标签: javascript reactjs this