React-列表和Key的综合示例

轻鸟评职场技能 2024-05-19 08:30:48
import React from "react";import 'bootstrap/dist/css/bootstrap.min.css';const infoMap = { titleInfo: '列表和Key简单示例', titleOne: 'React.js开发示例', contentOne: 'React.js组件的应用开发', titleTwo: 'React.js安装方法', contentTwo: '可以使用npm安装',}const numbers = [1, 2, 3];function NumberList(pros) { const numbers = pros.numbers; const listItems = numbers.map((number) => <li key={number.toString()}>{number}</li>); return ( <ul>{listItems}</ul> );}function ListItem(props) { // 不需要指定Key的示例 return <li>{props.value}</li>;}function NumberListTwo(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // key应该在数组的上下文中被指定的示例 <ListItem key={number.toString()} value={number}/> ); return ( <ul>{listItems}</ul> );}function Blog(props){ const sidebar = ( <ul> {props.posts.map((post) => <li key={post.id}>{post.title}</li> )} </ul> ); const content = props.posts.map((post) => <div key={post.id}> <h3>{post.title}</h3> <p>{post.content}</p> </div> ); return ( <div> {sidebar} <hr /> {content} </div> );}const posts =[ {id: 1, title: infoMap.titleOne, content: infoMap.contentOne}, {id: 2, title: infoMap.titleTwo, content: infoMap.contentTwo},];const ListAndKeyExample = () => { return ( <span> <h3>{infoMap.titleInfo}</h3> <NumberList numbers={numbers} /> <hr/> <NumberListTwo numbers={numbers} /> <hr/> <Blog posts={posts} /> </span> );}export default ListAndKeyExample;

运行效果:

0 阅读:0