React组件Key应该有多独特? [英] How unique should a React component Key be?

查看:90
本文介绍了React组件Key应该有多独特?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个快速的问题:子键必须是唯一的范围是什么?这只是父组件还是整个应用程序?

This is a quick one: what is the scope in which the children keys have to be unique? Is this just the parent component or the whole app?

如果后者为真,那么它是否意味着反应差异算法会在元素移动时保留一个元素?

If the latter is true, does it mean react diff algorithm will preserve an element when its moved across parent components?

推荐答案

在其兄弟姐妹中独一无二,所以直接在其父级之下。然而,父组件的子组可以再次使用相同的键,因为最终,react将组成当前组件及其所有祖先的键中的完整键。下面的示例仅包含自动生成的密钥,但如果您提供自己的密钥,则会使用它。

Unique within its siblings, so the level directly under its parent. The children of the parent component however can use the same key again, because finally, react will compose the complete key out of the key of the current component and all of its ancestors. The example below only contains auto-generated keys, but if you provide your own key, it will be used instead.

您可以在Chrome开发者工具(标签元素)中看到撰写的ID。

You can see the composed ID's in Chrome developer tools (tab Elements).

这篇关于React组件Key应该有多独特?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆