【问题标题】:how to remove on html of jsx element, using map function reactjs如何使用地图功能reactjs删除jsx元素的html
【发布时间】:2017-04-20 23:53:21
【问题描述】:

我有一个愚蠢的问题,我的代码工作得很好,但是我有一个问题,我必须再添加一个

标签,而不只是在网页上显示一些东西,

请阅读评论,任何人都可以告诉我如何编写这段代码,所以我不必使用两个 html 标记,我不想标记,我只需要一个, 请阅读评论

    showOrderItem(){

                    const orderItems=this.props.orderItems
                    const orderItem=orderItems.map((order,item)=>
                    <p>// if i remove this it wont display me any thing
        { order.quantityEditing?
                        //if i remove these p tag, it will display me the 
            error, adjacent jsx element must be wrapped in closing tag.
                        <p>{order.quantity} {order.itemName}</p>
                        :''

                    }</p>
                    );
    //Please read the comment below
                    return orderItem
                }

还有一件事,为此请给我一些阅读链接,而不是在这里回答, 这是什么意思相邻的jsx元素必须用结束标签包裹,我的理解——元素应该写在一个根元素中, 所以根据我的理解,我在这段代码中添加了一个 div 标签,但我想我对它的理解是错误的, 谢谢你的时间

【问题讨论】:

  • React 组件必须只返回一个节点,这意味着在任何需要显示多个子节点的情况下,您总是必须将它们包装在一个包含节点中。跨度>

标签: reactjs jsx


【解决方案1】:

您有一些语法错误。如果简写方法语法以花括号开头,则默认情况下不会返回值。但是,您可以用括号括起一个块以默认返回一个值,或者根本不包含任何大括号。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

我认为这是对您的代码的更正:

showOrderItem() { 
  const orderItems = this.props.orderItems;
  const orderItem = orderItems.map((order, item) => {
    if(order.quantityEditing) {
        return (
          <p>{order.quantity} {order.itemName}</p>
        );
    } else {
        return '';
    } 
  };
  return orderItem;
}

【讨论】:

  • 你可能也没有 else,jsx 在尝试渲染 undefined 时应该忽略它。除非您出于某种原因实际上想要空字符串。
猜你喜欢
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多