[英]inject extra element into jsx after last element of array?
How to render 'd' to below arrays? 如何将“ d”呈现到下面的数组?
const App = () => (
<div style={styles}>
{['a', 'b', 'c'].map((o, i) => {
return (<div>{o}</div>)
}
)}
</div>
);
Says I will assign ['a', 'b', 'c']
to const x
how can I use map and render new element after c
? 说我将
['a', 'b', 'c']
分配给const x
我如何使用地图并在c
之后呈现新元素? I can get last element like 我可以得到像
{
if(i === x.length - 1) { return('d') }
}
but c will be gone, how to create the 4th element? 但是c会消失,如何创建第四个元素?
You can return both items in an array from the map callback: 您可以从地图回调中返回数组中的两个项目:
const x = ['a', 'b', 'c']; const App = () => ( <div> {x.map((o, i) => { if(i === x.length - 1) { return [ <div key={i}>{o}</div>, <div key={i + 1}>d</div> ]; } return (<div key={i}>{o}</div>) } )} </div> ); ReactDOM.render( <App />, app );
<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="app"></div>
However, since you always add d to the end, you can just stick the tag after the loop: 但是,由于您总是将d末尾添加,因此您可以在循环后粘贴标签:
const x = ['a', 'b', 'c']; const App = () => ( <div> {x.map((o, i) => { return (<div key={i}>{o}</div>) } )} <div>d</div> </div> ); ReactDOM.render( <App />, app );
<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="app"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.