gpt4 book ai didi

javascript - react 教程 : TypeError: Cannot read property 'props' of undefined

转载 作者:行者123 更新时间:2023-12-03 13:05:22 26 4
gpt4 key购买 nike

我决定学习React并从官方教程开始。一切都很好,直到我的代码达到这种状态:

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 中收到以下错误:

TypeError: Cannot read property 'props' of undefined

...调试器在标记行处暂停(参见代码)。当我将鼠标悬停在 {this.props.author} 中的 this 时,我可以预览具有 props 属性和所有内容的对象。 .

最佳答案

使用函数声明(render() {}render: 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>
);
}
});

Example

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.

关于javascript - react 教程 : TypeError: Cannot read property 'props' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33957229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com