赞
踩
你将依赖 JavaScript 的特性,例如 for 循环 和 array 的 map() 函数 来渲染组件列表。
假设你有一个产品数组:
- const products = [
- { title: 'Cabbage', id: 1 },
- { title: 'Garlic', id: 2 },
- { title: 'Apple', id: 3 },
- ];
在你的组件中,使用 map() 函数将这个数组转换为 <li> 标签构成的列表:
- const listItems = products.map(product =>
- <li key={product.id}>
- {product.title}
- </li>
- );
-
- return (
- <ul>{listItems}</ul>
- );
注意, <li> 有一个 key 属性。对于列表中的每一个元素,你都应该传递一个字符串或者数字给 key,用于在其兄弟节点中唯一标识该元素。通常 key 来自你的数据,比如数据库中的 ID。如果你在后续插入、删除或重新排序这些项目,React 将依靠你提供的 key 来思考发生了什么。
- const products = [
- { title: 'Cabbage', isFruit: false, id: 1 },
- { title: 'Garlic', isFruit: false, id: 2 },
- { title: 'Apple', isFruit: true, id: 3 },
- ];
-
- export default function ShoppingList() {
- const listItems = products.map(product =>
- <li
- key={product.id}
- style={{
- color: product.isFruit ? 'magenta' : 'darkgreen'
- }}
- >
- {product.title}
- </li>
- );
-
- return (
- <ul>{listItems}</ul>
- );
- }

效果图如下:

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。