如何在 React JSX 中除最后一个元素之外的每个元素之后在 array.map 中添加逗号 [英] How to add a comma in array.map after every element except last element in React JSX

查看:77
本文介绍了如何在 React JSX 中除最后一个元素之外的每个元素之后在 array.map 中添加逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在数组的每个元素后添加尾随逗号以制作如下列表:

INV、INV、INV、INV

注意最后一个元素没有尾随逗号

当前正在使用 array.map 迭代列表:

var List = React.createClass({渲染:函数(){返回 (<div>{this.props.data.map(function(item) {返回<div>{item}</div>;})}

);}});var data = ["红色", "绿色", "蓝色"];React.render(<List data={data}/>, document.body);

解决方案

如评论所示,您可以使用:

<块引用>

array.map((item, index) => ({ (index ? ', ': '') + item }))

此外,由于您想内联显示文本,因此使用 div 是不合适的.相反,您可以/应该使用内联元素,例如 span

var List = React.createClass({渲染:函数(){返回 (<div>{this.props.data.map(function(item, index) {return <span key={`demo_snap_${index}`}>{ (index ? ', ' : '') + item }</span>;})}

);}});var data = ["红色", "绿色", "蓝色"];ReactDOM.render(, demo);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="demo"></div>

How can I add a trailing comma after every element of an array for making a list like:

INV, INV, INV, INV

Note that the last element doesn't have a trailing comma

Currently iterating the list with array.map:

var List = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.data.map(function(item) {
          return <div>{item}</div>;
        })}
      </div>
    );
  }
});

var data = ["red", "green", "blue"];

React.render(<List data={data} />, document.body);

解决方案

As commented you can use:

array.map((item, index) => ({ (index ? ', ': '') + item }))

Also, since you want to display text inline, using a div is not appropriate. Instead you can/should use an inline element like span

var List = React.createClass({
  render: function() {
    return (
      <div>
        {
          this.props.data.map(function(item, index) {
            return <span key={`demo_snap_${index}`}>{ (index ? ', ' : '') + item }</span>;
          })
        }
      </div>
    );
  }
});

var data = ["red", "green", "blue"];

ReactDOM.render(<List data={data} />, demo);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="demo"></div>

这篇关于如何在 React JSX 中除最后一个元素之外的每个元素之后在 array.map 中添加逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆