用ts重写React官方文档里的demo(5)——列表 & Key

78 阅读1分钟
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.'}
]

注意:

  1. 当不知道何时使用key时:在 map() 方法中的元素需要设置 key 属性。
  2. key 会传递信息给 React ,但不会传递给你的组件。如果你的组件中需要使用 key 属性的值,请用其他属性名显式传递这个值。