从对象数组渲染React组件 [英] Rendering React Components from Array of Objects
问题描述
我有一些名为station的数据,它是一个包含对象的数组。
I have some data called stations which is an array containing objects.
stations : [
{call:'station one',frequency:'000'},
{call:'station two',frequency:'001'}
]
我想为每个数组位置渲染一个ui组件。到目前为止,我可以编写
I'd like to render a ui component for each array position. So far I can write
var stationsArr = []
for (var i = 0; i < this.data.stations.length; i++) {
stationsArr.push(
<div className="station">
{this.data}
</div>
)
}
然后渲染
render(){
return (
{stationsArr}
)
}
问题是我正在打印所有数据。我只想显示一个像 {this.data.call}
这样的密钥,但是什么都不打印。
The problem is I'm getting all of the data printing out. I instead want to just show a key like {this.data.call}
but that prints nothing.
如何我可以遍历这些数据并为数组的每个位置返回一个新的UI元素吗?
How can I loop through this data and return a new UI element for each position of the array?
推荐答案
你可以映射列表到ReactElements的站点。
You can map the list of stations to ReactElements.
使用React> = 16,可以从同一个组件返回多个元素而无需额外的html元素包装。从16.2开始,有一个新语法<> 创建片段。如果这不起作用或IDE不支持,则可以使用< React.Fragment>
。在16.0和16.2之间,您可以使用非常简单的 polyfill 来表示碎片。
With React >= 16, it is possible to return multiple elements from the same component without needing an extra html element wrapper. Since 16.2, there is a new syntax <> to create fragments. If this does not work or is not supported by your IDE, you can use <React.Fragment>
instead. Between 16.0 and 16.2, you can use a very simple polyfill for fragments.
请尝试以下
// Modern syntax >= React 16.2.0
const Test = ({stations}) => (
<>
{stations.map(station => (
<div className="station" key={station.call}>{station.call}</div>
))}
</>
);
// Modern syntax < React 16.2.0
// You need to wrap in an extra element like div here
const Test = ({stations}) => (
<div>
{stations.map(station => (
<div className="station" key={station.call}>{station.call}</div>
))}
</div>
);
// old syntax
var Test = React.createClass({
render: function() {
var stationComponents = this.props.stations.map(function(station) {
return <div className="station" key={station.call}>{station.call}</div>;
});
return <div>{stationComponents}</div>;
}
});
var stations = [
{call:'station one',frequency:'000'},
{call:'station two',frequency:'001'}
];
ReactDOM.render(
<div>
<Test stations={stations} />
</div>,
document.getElementById('container')
);
不要忘记键
属性!
https://jsfiddle.net/69z2wepo/14377 /
这篇关于从对象数组渲染React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!