React - 列表 & Key
用 key 提取组件
元素的 key 只有放在就近的数组上下文中才有意义。
比方说,如果你提取出一个 ListItem
组件,你应该把 key 保留在数组中的这个 <ListItem />
元素上,而不是放在 ListItem
组件中的 <li>
元素上。
key 只是在兄弟节点之间必须唯一
key 会传递信息给 React ,但不会传递给你的组件。如果你的组件中需要使用 key
属性的值,请用其他属性名显式传递这个值
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: 'hello world', content: 'welcome to learning react!'}, {id: 2, title: 'installation', content: 'you can install react from npm.'} ]; ReactDOM.render( <Blog posts={posts} />, document.getElementById('root') );
Sep 17, 2021 03:52:49 PM
I was looking this amazing information for a long time. Thank you so much and good luck for nex post.
Chennai Escorts ||Escorts Service in Chennai ||Chennai Escorts service ||Chennai Escort
May 04, 2023 01:01:57 AM
Pavzi Post is a startup by passionate webmasters and bloggers who have a passion to provide engaging content which is accurate, interesting and worthy to read. Pavzi Post is a startup by passionate webmasters and bloggers who have a passion to provide engaging content which is accurate, interesting and worthy to read. We are more like a web community. We provide you with the finest web content on each and every topic possible with help of the editorial and content team. We are more like a web community where you can pavzi.com find different information, resources, and topics on day-to-day incidents or news.