returning paired elements in React JSX

血红的双手。 提交于 2019-12-22 03:48:13

问题


The Problem:

In React, you want to create a DOM structure by mapping an array, but each item in the array should return 2 elements. e.g.

import React from 'react'
import _ from 'lodash'

let { Component } = React

export default class DataList extends Component {
  render () {
    let array = [
      {def: 'item1', term: 'term1', obj1: 'rand'}, 
      {def: 'item2', term: 'term2'}
    ]
    return (
      <dl>
        {_.map(array, (item) => {
          return (
            <dt>{item.def}</dt>
            <dd>{item.term}</dd>
          )
        })}
      </dl>
    )
  }
}

React doesn't let you render siblings without wrapping them in a container element, which would break the DOM structure here.


回答1:


You could do something simpler with reduce like this:

import React, { Component } from 'react';

export default class DataList extends Component {
  render () {
    const array = [
      {def: 'item1', term: 'term1', obj1: 'rand'}, 
      {def: 'item2', term: 'term2'}
    ];

    return (
      <dl>
        {array.reduce((acc, item, idx) => {
            return acc.concat([
                <dt key={`def-${idx}`}>{item.def}</dt>,
                <dd key={`term-${idx}`}>{item.term}</dd>
            ]);
        }, [])}
      </dl>
    );
  }
}

DEMO :: https://jsfiddle.net/rifat/caray95v/




回答2:


React 16.2 added support for Fragments, you can use it like this:

return (
  <dl>
    {_.map(array, (item) => {
      return (
        <Fragment>
          <dt>{item.def}</dt>
          <dd>{item.term}</dd>
        </Fragment>
      )
    })}
  </dl>
)

You can also use Fragment with empty tag like this:

return (
  <dl>
    {_.map(array, (item) => {
      return (
        <>
          <dt>{item.def}</dt>
          <dd>{item.term}</dd>
        </>
      )
    })}
  </dl>
)

But keep in mind that if you want to use the key attribute on Fragment tag you have to use the full version of it. More info on this react's blog




回答3:


I found the simplest way to achieve this is to map over the object keys (lodash supports this) for each item of the array and conditionally render each type of element.

import React from 'react'
import _ from 'lodash'

let { Component } = React

export default class DataList extends Component {
  render () {
    let array = [
      {def: 'item1', term: 'term1', obj1: 'rand'}, 
      {def: 'item2', term: 'term2'}
    ]

    return (
      <dl>
        {_.map(array, (item) => {
          return _.map(item, (elem, key) => {
            if (key === 'def') {
              return <dt>{elem}</dt>
            } else if (key === 'term') {
              return <dd>{elem}</dd>
            }
          })
        })}
      </dl>
    )
  }
}


来源:https://stackoverflow.com/questions/35770253/returning-paired-elements-in-react-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!