简体   繁体   English

如何在 array.map 中除 React JSX 中的最后一个元素之外的每个元素之后添加逗号

[英]How to add a comma in array.map after every element except last element in React JSX

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 :当前使用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 })) array.map((item, index) => ({ (index ? ', ': '') + item }))

Also, since you want to display text inline, using a div is not appropriate.此外,由于您想内联显示文本,因此不适合使用 div。 Instead you can/should use an inline element like span相反,您可以/应该使用像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>

Use the CSS adjacent sibling combinator ( + ) to add pseudo element ( ::before ) with a comma to all sibling items, but the 1st:使用 CSS 相邻兄弟组合符( + ) 以逗号添加伪元素 ( ::before ) 到所有兄弟项目,但第一个:

 const List = ({ data }) => ( <div> {data.map((item, idx) => ( <span className="item" key={idx}>{item}</span> ))} </div> ); var data = ["red", "green", "blue"]; ReactDOM.render(<List data={data} />, demo);
 .item + .item::before { display: inline-block; white-space: pre; content: ", "; }
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="demo"></div>

Another option is to create a generic component that expects a list of items, and an optional separator, and maps the children to include the separator.另一种选择是创建一个通用组件,它需要一个项目列表和一个可选的分隔符,并映射子项以包含分隔符。 This uses the index method detailed in Rajesh's answer .这使用了Rajesh 的回答中详述的 index 方法。

Note: due to the old BabelJS version used by the SO snippet, I need to use <Fragment> instead of the shorter <> for a fragment.注意:由于 SO 片段使用的旧 BabelJS 版本,我需要使用<Fragment>而不是较短的<>片段。

 const { Children, Fragment } = React; const AddSeparators = ({ children, separator = ', ' }) => Children.map(children, (child, idx) => ( <Fragment> {idx ? separator : ''} {child} </Fragment> )); const List = ({ data }) => ( <div> <AddSeparators separator=" | "> {data.map((item, idx) => ( <span key={idx}>{item}</span> ))} </AddSeparators> </div> ); var data = ["red", "green", "blue"]; ReactDOM.render(<List data={data} />, demo);
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="demo"></div>

What you can do is, check the index of item, if index is not equals to the last item render the , otherwise nothing.你可以做的是,检查项目的索引,如果索引不等于最后一个项目,则渲染,否则什么都没有。

Write it like this:像这样写:

{
    this.props.data.map((item, i, arr) => <span>{item} {i != (arr.length-1) ? ',' : ''}</span>)
}

You can also store the total data length in a separate variable and instead of checking the arr.length in each iteration check with that variable.您还可以将总数据长度存储在单独的变量中,而不是在每次迭代中使用该变量检查arr.length

Working example:工作示例:

 var List = React.createClass({ render: function() { return ( <div> { this.props.data.map((item, i, arr) => <span>{item} {i != (arr.length-1) ? ', ' : ''}</span>) } </div> ); } }); var data = ["red", "green", "blue"]; ReactDOM.render(<List data={data} />, document.body);
 <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>

 const data = ["red", "green", "blue"]; class List extends React.Component{ render(){ return( <div> {this.props.data.map((item, index) => { return <span>{ (index ? ', ' : '') + item }</span>; })} </div> ) } } ReactDOM.render( <List data={data}/>, document.getElementById('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>

这样做:

<div>{array.join(',')}</div>

try array.toString()尝试array.toString()

you will get INV, INV, INV, INV你会得到INV, INV, INV, INV

正如@toxxiczny 所指定的,我们可以在javascript 中使用连接。

array.join(', ');

I know this is late, but this is BY FAR the easiest way without any functions.我知道这已经晚了,但这是迄今为止最简单的方法,没有任何功能。 Works great in inline statements and requires no separate functions or mapping if that's what's needed in your case.在内联语句中效果很好,如果您的情况需要,则不需要单独的函数或映射。

 const items = [1, 2, 3, 4, 5]; console.log("Items: " + "" + items + ".")

The ""+ before the array adds the comma for some reason I don't fully understand why.数组之前的 ""+ 出于某种原因添加了逗号,我不完全理解为什么。

 var List = React.createClass({ render: function() { return ( <div> {this.props.data.map(function(item) { return <div>{item.join(",")}</div>; })} </div> ); } }); var data = ["red", "green", "blue"]; React.render(<List data={data} />, document.body);

Comma + Natural word wrapping逗号 + 自然换行

Here's a way to do it while maintaining proper linebreaks with the comma.这是一种方法,同时使用逗号保持适当的换行符。

['red', 'green', 'blue']
  .reduce((a, b, index) => [
    ...a,
    <Fragment key={`comma-${index}`}>{', '}</Fragment>,
    <Fragment key={`value-${index}`}>{b}</Fragment>
  ], [])
  .slice(1);

Why not group the comma in the map function?为什么不将逗号分组在map function 中?

In word-wrapping scenarios, the comma is attached to the following word, when it should be attached to the immediate left word.在自动换行的情况下,逗号附加在后面的单词上,而它应该附加在紧邻的左边单词上。

Why not [...a, ',', b] ?为什么不[...a, ',', b]

React needs a key to map the proper item within the virtual DOM (to avoid repaints on re-render). React 需要 map 虚拟 DOM 中正确项目的key (以避免重新渲染时重绘)。 Plus it won't throw a key warning on lower environments另外,它不会在较低的环境中发出key警告

Why is there slice ?为什么会有slice

Because of the 3rd argument of reduce , the first iteration always adds a comma.由于reduce的第三个参数,第一次迭代总是添加一个逗号。 slice(1) shifts the array by 1. This also makes it easier to understand the code instead of adding a logic statement inside the reduce function. slice(1)将数组移动 1。这也更容易理解代码,而不是在 reduce function 内部添加逻辑语句。

Do I have to use <Fragment /> ?我必须使用<Fragment />吗?

You can use any component instead of Fragment , like a span or your custom component.您可以使用任何组件而不是Fragment ,例如span或您的自定义组件。

 var List = React.createClass({ render: function() { return ( <div> {this.props.data.map(function(item) { return <div>{item.join(",")}</div>; })} </div> ); } }); var data = ["red", "green", "blue"]; React.render(<List data={data} />, document.body);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

enter code here在此处输入代码


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM