我可以在 Javascript 或 JSX 中将解包对象作为参数传递吗?

Can I pass unpacking object as parameter in Javascript or 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"));

在这段代码中,我只是使用data将参数传递给Comment。由于 dataobject,类似于 Python 的 dict。所以我想知道,我可以将 data 作为解包 object 传递吗?就像使用 ** 是 Python:

>>> def show(**kwargs):
...     return kwargs
... 
>>> items = {'a': 1, 'b': 2}
>>> print(show(**items))
{'a': 1, 'b': 2}

您可以使用 spread attributes 语法。

正如@AlexPalcuie 上面的回答,您可以使用 object spread 来完成 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>
        );
    }
});