Renders a list of elements from an array of primitives.
- Use the value of the
isOrderedprop to conditionally render a<ol>or<ul>list. - Use
Array.prototype.mapto render every item indataas a<li>element, give it akeyproduced from the concatenation of the its index and value. - Omit the
isOrderedprop to render a<ul>list by default.
代码实现
function DataList({ isOrdered, data }) {
const list = data.map((val, i) => <li key={`${i}_${val}`}>{val}</li>);
return isOrdered ? <ol>{list}</ol> : <ul>{list}</ul>;
}
使用样例
const names = ['John', 'Paul', 'Mary'];
ReactDOM.render(<DataList data={names} />, document.getElementById('root'));
ReactDOM.render(<DataList data={names} isOrdered />, document.getElementById('root'));