spe*_*ll4 3 javascript python reactjs react-jsx
var data = [
{author: 'foo', comment: 'nice'},
{author: 'bar', comment: 'wow'}
];
var CommentBox = React.createClass({
render: function () {
var CommentNodes = this.props.data.map(function (comment) {
return (
<Comment author={comment.author} comment={comment.comment}>
</Comment>
);
});
return (
<div className="comment-box">
{CommentNodes}
</div>
);
}
});
var Comment = React.createClass({
render: function () {
return (
<div className="comment-box comment">
<h2 className="comment-author">
{this.props.author}
</h2>
{this.props.comment}
</div>
);
}
});
React.render(<CommentBox data={data}/>, document.getElementById("example"));
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我只是将参数传递给Commentusing data。由于data是 a object,它类似于 Python 的dict. 所以我想知道,我可以data作为解包通过object吗?喜欢使用的**是 Python:
>>> def show(**kwargs):
... return kwargs
...
>>> items = {'a': 1, 'b': 2}
>>> print(show(**items))
{'a': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)
正如上面的@AlexPalcuie 回答的那样,您可以使用对象传播来准确完成 python**运算符所做的工作。
所以这相当于你上面的代码:
var CommentBox = React.createClass({
render: function () {
var CommentNodes = this.props.data.map(function (comment) {
return (
<Comment {...comment}>
</Comment>
);
});
return (
<div className="comment-box">
{CommentNodes}
</div>
);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2059 次 |
| 最近记录: |