首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >React的列表组件必须要有key?

React的列表组件必须要有key?

原创
作者头像
Learn-anything.cn
发布2021-11-28 06:09:46
发布2021-11-28 06:09:46
8690
举报
文章被收录于专栏:learn-anything.cnlearn-anything.cn
一、列表组件没有key属性会warning?
1、key提高性能

当创建列表组件时,必须给每一个元素设置 key 属性,否则会有警告: a key should be provided for list items。如果元素没有key属性,React很难判断元素应该怎么渲染?如果元素有key值,那么React只对匹配key值的元素,进行更改等渲染操作,这样极高提升了运行性能。

二、列表组件使用说明
1、错误用法
代码语言:txt
复制
function ListItem(props) {
    const value = props.value;
    return (
        // 错误!你不需要在这里指定 key:
        <li key={value.toString()}>
            {value}
        </li>
    );
}

function NumberList(props) {
    const numbers = props.numbers;
    const listItems = numbers.map((number) =>
        // 错误!元素的 key 应该在这里指定:
        <ListItem value={number} />
    );
    return (
        <ul>
            {listItems}
        </ul>
    );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
    <NumberList numbers={numbers} />,
    document.getElementById('root')
);
2、正确用法
代码语言:txt
复制
function ListItem(props) {
    // 正确!这里不需要指定 key:
    return <li>{props.value}</li>;
}

function NumberList(props) {
    const numbers = props.numbers;
    const listItems = numbers.map((number) =>
        // 正确!key 应该在数组的上下文中被指定
        <ListItem key={number.toString()} value={number} />
    );
    return (
        <ul>
            {listItems}
        </ul>
    );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
    <NumberList numbers={numbers} />,
    document.getElementById('root')
);
3、key值无法读取

key 值会传递给 React ,但不会传递给组件。如果需要使用 key 值,请用其他属性(譬如id):

代码语言:txt
复制
# Post 组件可以读出 props.id,但是不能读出 props.key
const content = posts.map((post) =>
    <Post
        key={post.id}
        id={post.id}
        title={post.title} />
);
4、唯一性

key 在兄弟节点间必须唯一,但全局不需要唯一。

代码语言:txt
复制
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')
);
参考文档

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、列表组件没有key属性会warning?
    • 1、key提高性能
  • 二、列表组件使用说明
    • 1、错误用法
    • 2、正确用法
    • 3、key值无法读取
    • 4、唯一性
  • 参考文档
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档