React Tutorial:TypeError:无法读取未定义的属性'props' [英] React Tutorial: TypeError: Cannot read property 'props' of undefined
问题描述
我决定学习React并开始使用官方教程。一切都很好,直到我达到我的代码状态:
I decided to learn React and started with the official tutorial. All is good until I get to this state of my code:
var CommentBox = React.createClass({
render: () => {
return (
<div className="commentBox">
<h1> Comments </h1>
<CommentList />
<CommentForm />
</div>
);
}
});
var CommentForm = React.createClass({
render: () => {
return (
<div className="commentForm">
Hello, world! I am a comment form;
</div>
);
}
});
var Comment = React.createClass({
rawMarkup: () => {
var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
return {__html: rawMarkup};
},
render: () => {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2> // <--- [[[[[[ ERROR IS HERE ]]]]]]
<span dangerouslySetInnerHtml={this.rawMarkup} />
</div>
);
}
});
var CommentList = React.createClass({
render: () => {
return (
<div className="commentList">
<Comment author="Pete Hunt">This is one comment</Comment>
<Comment author="Jordan Walke">This is *another* comment yo</Comment>
</div>
);
}
});
ReactDOM.render(
<CommentBox />,
document.getElementById('content')
);
当我尝试运行它时,我在devtools中收到以下错误:
When I try to run it, I get the following error in devtools:
TypeError:无法读取未定义的属性'props'
TypeError: Cannot read property 'props' of undefined
。 ..并且调试器在标记的行处暂停(参见代码)。当我在 {this.props.author}
中鼠标悬停这个
时,我得到了一个具有<的对象的预览code>道具属性和一切......
...and the debugger pauses at the marked line (see code). When I mouseover this
in {this.props.author}
, I get a preview of the object which has the props
property and everything...
推荐答案
使用函数声明( render(){}
或 render:function {}
)而不是箭头函数 render :() => {}
Use function declaration ( render() {}
or render: function {}
) instead of arrow function render: () => {}
var Comment = React.createClass({
rawMarkup() {
var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
return {__html: rawMarkup};
},
render() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHtml={this.rawMarkup} />
</div>
);
}
});
arrow function
与函数表达式相比,expression具有更短的语法,并且词法绑定此值(不绑定它自己的this,arguments,super或new.target)。
箭头函数始终是匿名的。
An
arrow function
expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.
这篇关于React Tutorial:TypeError:无法读取未定义的属性'props'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!