本文介绍了在React JSX中返回配对元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题:
在React中,您希望通过映射数组来创建DOM结构,但数组中的每个项目都应返回2个元素。例如
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不允许你渲染兄弟姐妹而不将它们包装在容器元素中,这会破坏DOM结构。
React doesn't let you render siblings without wrapping them in a container element, which would break the DOM structure here.
推荐答案
你可以用 reduce
做一些更简单的事情:
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 ::
这篇关于在React JSX中返回配对元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!