作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何访问组件的 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/
我是一名优秀的程序员,十分优秀!