【问题标题】:How to pass extra props down to children of arry.map如何将额外的道具传递给 arry.map 的孩子
【发布时间】:2016-12-08 18:57:11
【问题描述】:

我一直在尝试将自己的额外道具传递给使用 .map 函数创建的孩子,但我未能成功传递它们。

这是我的代码:

export const CommentsListShanghai = (props) => {
  const newTimestamp = props.timestamp;
  console.log(newTimestamp);
  const comments = props.comments;
  if (comments.length > 0 ) {
   return (
    <ButtonToolbar className="comment-list">
    {comments.map((com) => {
      return ( 
        com.adminSpark ? 
          <CommentsModal 
            className="comments-modal"
            data-comments-modal={props.newTimestamp}
            key={ com._id } 
            comment={ com } 
            city={com.city} 
            person={com.person} 
            location={com.location} 
            title={com.title} 
            content={com.content} 
            fileLink={com.fileLink} 
            timestamp={com.timestamp} 
            createdBy={com.createdBy}
            /> :
          <CommentsModal 
            key={ com._id } 
            comment={ com } 
            city={com.city} 
            person={com.person} 
            location={com.location} 
            title={com.title} 
            content={com.content} 
            fileLink={com.fileLink} 
            timestamp={com.timestamp} 
            createdBy={com.createdBy} />
        )
    })}
    </ButtonToolbar> 
   );
  } else {
    return (
      <Alert bsStyle="warning">No sparks yet. Please add some!</Alert>
    );
  }
};

CommentsListShanghai.propTypes = {
  comments: React.PropTypes.array,
};

我能够传递我创建的 cmets const 的所有道具,问题是除了这些道具之外,我还需要传递 CommentsListShanghai 中可用的额外道具。我怎样才能将额外的道具传递给这个数组?

我可以毫无问题地使用 console.log(newTimestamp),但不明白如何将其传递给 .map 函数。

【问题讨论】:

    标签: javascript reactjs meteor


    【解决方案1】:

    代替

    data-comments-modal={props.newTimestamp}
    

    随便用

    data-comments-modal={props.timestamp}
    

    这里的props还是指CommentsListShanghai的上下文。

    【讨论】:

    • 我怎样才能将这些道具添加到模态中?我试过 newTimestamp={timestamp} 但这不起作用
    • 实际上我确实在我的模态组件中没有看到它们。称为data-cmets-modal。但是我现在如何在 Modal 中使用这些?
    • 当您在组件上设置属性时声明这些属性,例如className、data-comments-modal、key、comment、city。这些现在都是CommentsModal 的道具。无论您在哪里定义CommentsModal,您都可以访问这些道具。例如,CommentsModal = (props) =&gt; (&lt;div&gt;&lt;/div&gt;)
    • 很奇怪,当我现在尝试使用 this.props.data-cmets-modal 访问这些道具时,我收到一个错误,即 cmets 未定义。
    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 2017-06-03
    • 2018-04-09
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多