我有json数组像这样:
{
area:1,
label: "element1"
},
{
area:3,
label: "element3"
},
{
area:1,
label: "element2"
},
{
area:2,
label: "element2_1"
}
我会渲染一个元素:
1区 -
部件1
在element2
区域2- element2_1
第3区 - 元素3
我现在已经这样做了,但现在我不知道如何分组属性“area”
this.state.areas.map(function(el, key){
return (
<div>
<span><strong>{el.label}</strong></span>
</div>
);
)}
答案 0 :(得分:0)
如果您将标签制作成阵列,则可以像这样对它们进行分组和渲染。
var Hello = React.createClass({
componentWillMount: function() {
this.state = {
area: [
{
area: 1,
label: ['element 1', 'element 2']
},
{
area: 2,
label: ['element 2_1']
},
{
area: 3,
label: ['element 3']
}
]
};
},
render: function() {
return (
<div>
{ this.state.area.map(function(el, key) {
return (
<div key={el.area}>
<span>
<strong>
{ el.label.map(function(label) {
return (
<span key={label}>{label}</span>
)
}) }
</strong>
</span>
</div>
);
}) }
</div>
)
}
});
ReactDOM.render(
<Hello /> ,
document.getElementById('container')
);
<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="container"></div>
答案 1 :(得分:0)
我想这可以帮助你https://jsfiddle.net/69z2wepo/69759/
const myState = [{
area:1,
label: "element1"
},
{
area:3,
label: "element3"
},
{
area:1,
label: "element2"
},
{
area:2,
label: "element2_1"
}];
const ShowArea = (props) => <div><strong>Area {props.area}</strong><span>{props.children}</span></div>
const ShowLabel = (props) =>{
return(<span style={{paddingLeft:'10px'}} key={props.label}><strong>{props.label}</strong></span>)
};
var Hello = React.createClass({
render: function() {
const CompareByArea = (a,b) => a.area > b.area;
const OrderList = myState.sort(CompareByArea);
let newState = {};
OrderList.forEach(element=>{
if(!newState[element.area])
newState[element.area] = [];
newState[element.area].push({label: element.label});
});
const keys = Object.keys(newState);
const Elements = keys.map((key) => <ShowArea key={key} area={key} >
{newState[key].map(ShowLabel)}
</ShowArea>);
return (<div>{Elements}</div>)
}
});
ReactDOM.render(
<Hello/>,document.getElementById('container')
);