bit*_*eam 23 javascript reactjs
我决定学习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')
);
Run Code Online (Sandbox Code Playgroud)
当我尝试运行它时,我在devtools中收到以下错误:
TypeError:无法读取undefined的属性'props'
...并且调试器在标记的行处暂停(参见代码).当我鼠标悬停this时{this.props.author},我得到了具有props属性和所有内容的对象的预览...
Ale*_* T. 34
使用函数声明(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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
一个
arrow function相比函数表达式表达具有较短的语法和词汇结合此值(不结合其自身的此,自变量,超级或new.target).箭头功能始终是匿名的.
我有相同的错误消息:
无法读取undefined的属性'props'
... 但是从不同的原因:当this从函数内部调用时,javascript无法到达变量,因为this它位于外部范围内.(注意:我在ES5)
在这种情况下,只需this在函数之前(在组件的范围内)存储在另一个变量中:var that = this;
然后你就可以that.props从函数中调用了.
希望这有助于其他有错误信息的人.
详细示例如下:
render: function() {
var steps = [];
var that = this; // store the reference for later use
var count = 0;
this.props.steps.forEach(function(step) {
steps.push(<Step myFunction={function(){that.props.anotherFunction(count)}}/>); // here you are
count += 1;
});
return (
<div>{steps}</div>
)
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32361 次 |
| 最近记录: |