How to render react components by using map and join?

后端 未结 14 2165
南旧
南旧 2020-12-07 15:30

I have one component which is going to display Array of String. The code looks like this:

React.createClass({
  render() {
     
this.props
相关标签:
14条回答
  • 2020-12-07 16:07

    If I just want to render a comma-separated array of components, I usually find reduce too verbose. A shorter solution in such cases is

    {arr.map((item, index) => (
      <Fragment key={item.id}>
        {index > 0 && ', '}
        <Item {...item} />
      </Fragment>
    ))}
    

    {index > 0 && ', '} will render a comma followed by a space in front of all array items except the first one.

    If you want to separate the second-to-last item and the last one by something else, say the string ' and ', you can replace {index > 0 && ', '} with

    {index > 0 && index !== arr.length - 1 && ', '}
    {index === arr.length - 1 && ' and '}
    
    0 讨论(0)
  • 2020-12-07 16:08

    Use nested array to keep "," outside.

      <div>
          {this.props.data.map((element, index) => index == this.props.data.length - 1 ? <span key={index}>{element}</span> : [<span key={index}>{element}</span>, ", "])}
      </div>
    

    Optimize it by saving the data to array and modify last element instead of checking if its last element all the time.

      let processedData = this.props.data.map((element, index) => [<span key={index}>{element}</span>, ", "])
      processedData [this.props.data.length - 1].pop()
      <div>
          {processedData}
      </div>
    
    0 讨论(0)
提交回复
热议问题