【问题标题】:Can I pass unpacking object as parameter in Javascript or JSX?我可以在 Javascript 或 JSX 中将解包对象作为参数传递吗?
【发布时间】:2015-09-15 18:35:40
【问题描述】:
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:

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

【问题讨论】:

  • 看起来 data 是一个数组,this.props.data.map 正在解包数组。

标签: javascript python reactjs react-jsx


【解决方案1】:

您可以使用spread attributes 语法。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-17
      • 2015-12-29
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 2021-02-02
      相关资源
      最近更新 更多