我正在尝试浏览对象属性(此示例的名称)并在函数中的easy循环中列出它们。我发现了一些非常尴尬的方法,但这似乎不对。
这是我得到的:
<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="root"></div>
was compiled with optimization - stepping may behave oddly; variables may not be available.
有更好的方法吗? 我只需要一个循环来遍历对象数组,列出所需的属性并创建许多html节点之一。
答案 0 :(得分:2)
您可以简单地映射ItemsToSell
数组
const ItemsToSell = [{"Name":"Cup","Price":"99.99"},{"Name":"IPhone","Price":"99.99"},{
"Name":"Pen","Price":"99.99"}]
function ListItem(props) {
return <li>{props.value}</li>;
}
function NumberList(props) {
return (
<ul>
{ItemsToSell.map((obj, index) =>
<ListItem key={index} value={obj.Name} />
)}
</ul>
);
}
ReactDOM.render(
<NumberList />,
document.getElementById('root')
);
&#13;
<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="root"></div>
&#13;
答案 1 :(得分:1)
为什么不迭代ItemsToSell
数组?您不必再添加另一个。
注意:在循环元素时包含key
属性,否则您将收到错误。
const ItemsToSell = [{"Name":"Cup","Price":"99.99"},{"Name":"IPhone","Price":"99.99"},{
"Name":"Pen","Price":"99.99"}]
function ListItem(props) {
return <li>{props.value}</li>;
}
function NumberList(props) {
return (
<ul>
{ItemsToSell.map((elem, index) =>
<ListItem value={elem.Name} key={index} />
)}
</ul>
);
}
ReactDOM.render(
<NumberList />,
document.getElementById('root')
);
<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="root"></div>