interface Props {
posts:{
id: number,
title?: string,
content?: string
}[]
}
export function Blog(props: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}
{content}
</div>
)
}
export const posts = [
{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'}
]
注意:
- 当不知道何时使用key时:在
map() 方法中的元素需要设置 key 属性。
- key 会传递信息给 React ,但不会传递给你的组件。如果你的组件中需要使用
key 属性的值,请用其他属性名显式传递这个值。