gpt4 book ai didi

reactjs - 如何从reactjs组件访问 "key"属性

转载 作者:行者123 更新时间:2023-12-03 12:59:15 25 4
gpt4 key购买 nike

如何访问组件的 key 属性。我以为它会在 this.props 中,但事实并非如此。

例如

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

如果我这样做的话,也会在产品列表中

console.log(this.props)

返回

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

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

此外,键属性在整个组件中必须是唯一的,还是在渲染它的循环或集合中必须是唯一的?

最佳答案

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

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

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 - 如何从reactjs组件访问 "key"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33682774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com