javascript React.js 0.12 中的 this.key
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26657023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
This.key in React.js 0.12
提问by Pierlo Upitup
With the release of version 0.12 this.props.key
is no longer available inside a component, however it sounds like you can simply replace that with this.key
and everything should work as expected.
随着 0.12 版的发布,this.props.key
组件内不再可用,但听起来您可以简单地将其替换为this.key
,一切都应该按预期工作。
From the React v0.12 docs:
This means that you need to rename: someElement.props.key -> someElement.key
这意味着您需要重命名: someElement.props.key -> someElement.key
However when I try to access this.key
within the render() function of my component, i get an undefined
.
但是,当我尝试this.key
在组件的 render() 函数中访问时,我得到一个undefined
.
See my pen to illustrate the issue: http://codepen.io/anon/pen/jaczr?editors=100
看我的笔来说明这个问题:http: //codepen.io/anon/pen/jaczr?editors=100
Also:
还:
Instances of a React Component are created internally in React when rendering. These instances are reused in subsequent renders, and can be accessed in your component methods as this.
React 组件的实例在渲染时在 React 内部创建。这些实例在后续渲染中重用,并且可以在您的组件方法中访问。
How am I supposed to access a component's key?
我应该如何访问组件的密钥?
UPDATE
更新
There is this issue on GitHubthat clarifies a lot. Thanks to HEAPfor mentioning it.
回答by Mike Driver
What the docs actually recommend (although it's badly worded) is that you should treat key
and ref
as internal to React and not accessible inside the component. If you need to know the key, simply pass it as another property with a different name and then access it on this.props
as normal.
文档实际上建议(尽管措辞不好)是您应该将key
和ref
视为 React 内部的,并且不能在组件内部访问。如果您需要知道密钥,只需将其作为具有不同名称的另一个属性传递,然后this.props
像往常一样访问它。
Quote from above:
引用自上:
You can no longer access this.props.ref and this.props.key from inside the Component instance itself. So you need to use a different name for those props.
您不能再从 Component 实例本身内部访问 this.props.ref 和 this.props.key。所以你需要为这些道具使用不同的名称。
An example would be:
一个例子是:
<MyComponent key={foo} reactKey={foo} />
Then accessing inside as this.props.reactKey
.
然后以this.props.reactKey
.