如何访问“密钥"来自 reactjs 组件的属性 [英] How to access the "key" property from a reactjs component

查看:16
本文介绍了如何访问“密钥"来自 reactjs 组件的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问组件的 key 属性.我以为它会在 this.props 中,但它不是.

How can I access the key property of a component. I thought it would be in this.props but it's not.

例如

<ProductList
    key = {list.id}
    listId = {list.id}
    name = {list.name}
    items = {list.items}
/>

如果我这样做,在产品列表中

and in product list if I do

console.log(this.props)

返回

Object {listId: "list1", name: "Default", items: Array[2]}

根本没有关键属性.我可以创建另一个属性并为其分配相同的值,但由于 key 属性已被使用,这似乎是多余的.

With no key property at all. I can create another property and assign the same value to it, but it seems redundant since the key property is already being used.

此外,key 属性是否必须在整个组件中是唯一的,或者只是在它被呈现的循环或集合中?

Also, does the key property have to be unique in the entire component, or just in the loop or collection it's being rendered from?

推荐答案

key 属性由 React 在幕后使用,不会向您公开.您将需要使用自定义属性并将该数据传入.我建议使用语义上有意义的属性名称;key 仅用于在协调过程中帮助识别 DOM 节点,因此使用另一个名为 listId 的属性是有意义的.

The key property is used by React under the hood, and is not exposed to you. You'll want to use a custom property and pass that data in. I recommend a semantically meaningful property name; key is only to help identify a DOM node during reconciliation, so having another property called listId makes sense.

key 属性对于整个组件不需要是唯一的,但我相信它对于您所在的嵌套级别应该是唯一的(通常是循环或集合).如果 React 检测到重复 key 的问题(在开发版本中),它会抛出一个错误:

The key property does not need to be unique for the whole component, but I believe it should be unique for the nesting level you're in (so generally the loop or collection). If React detects a problem with duplicate keys (in the development build), it will throw an error:

警告:flattenChildren(...):遇到两个使用相同密钥的孩子,.$a.子键必须是唯一的;当两个孩子共享一个密钥时,只会使用第一个孩子.

Warning: flattenChildren(...): Encountered two children with the same key, .$a. Child keys must be unique; when two children share a key, only the first child will be used.

这篇关于如何访问“密钥"来自 reactjs 组件的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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