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

2024-06-16 10:13:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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。因为data是一个object,它类似于Python的dict。所以我想知道,我可以把data作为解包object来传递吗?与使用**类似的是Python:

^{pr2}$

Tags: divdatareturnvarcommentfunctionrenderprops
1条回答
网友
1楼 · 发布于 2024-06-16 10:13:34

您可以使用spread attributes语法。在

网友
2楼 · 发布于 2024-06-16 10:13:34

正如@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>
        );
    }
});

相关问题 更多 >