javascript Reactjs:作为道具访问时未定义的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33661511/
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
Reactjs: Key undefined when accessed as a prop
提问by Nick Pineda
Tools: Reactjs 0.14.0 Vanilla Flux
工具:Reactjs 0.14.0 Vanilla Flux
I need unique identifiers for 2 reasons:
我需要唯一标识符有两个原因:
So let's say I have a list of messages that looks like this:
因此,假设我有一个如下所示的消息列表:
[
{
id: 1241241234, <-----The unique id is kept here
authorName:"Nick"
text:"Hi!"
},
...
]
And now I use a "Array.prototype.map()" to create "ownee"component(MessageListItem
) inside of the owner component MessageSection
现在我使用“Array.prototype.map()”在所有者组件内部创建“owneree”组件(MessageListItem
)MessageSection
function getMessageListItem)(message) {
return (
<MessageListItem key={message.id} message={message}/>
);
}
var MessageSection = React.createClass({
render: function(){
var messageListItems = this.state.messages.map(getMessageListItem);
<div>
{messageListItems }
</div>
}
});
But the this.props.key is undefined in the MessageListItem even though I know for a fact that is was defined when it was passed down.
但是 this.props.key 在 MessageListItem 中未定义,即使我知道它在传递时已定义的事实。
var ConvoListItem = React.createClass({
render: function() {
console.log(this.props.key); //Undefined
}
});
I'm guessing there is a reason that React is not letting "key" to be used as a prop.
我猜 React 不让“key”用作道具是有原因的。
Question:
问题:
If I can't use key as a prop - then what is the proper way to handle the duality need of keying and setting unique identifiers on a dynamic list of child elements that contain state?
如果我不能使用键作为道具 - 那么处理在包含状态的子元素的动态列表上键入和设置唯一标识符的二元性需求的正确方法是什么?
回答by Brigand
key and ref aren't really 'props'. They're used internally by react and not passed to components as props. Consider passing it as a prop such as 'id'.
key 和 ref 并不是真正的“道具”。它们由 react 在内部使用,而不是作为 props 传递给组件。考虑将其作为道具传递,例如“id”。
回答by J. Mark Stevens
It is best to use id. Then in the eventHandler you can have event.target.id.
最好使用id。然后在 eventHandler 中,您可以拥有 event.target.id。
function getMessageListItem)(message) {
return (
<MessageListItem key={message.id} id={message.id} message={message}/>
);
}
回答by Rakshit Sinha
As we already established in other answers that you can't use key
since it isn't passed as a prop and instead used internally by react. Here is my 2 cents as an alternative:
Since you're passing the entire array of messages as a prop while creating the <MessageListItem>
component, you don't necessarily need to pass another prop with id
. You can simply use {this.props.message.id}
whenever you need to use id.
正如我们在您不能使用的其他答案中已经建立的那样,key
因为它不是作为道具传递的,而是由 react 在内部使用的。这是我的 2 美分作为替代方案:
由于您在创建<MessageListItem>
组件时将整个消息数组作为道具传递,因此您不一定需要通过id
. 您可以{this.props.message.id}
在需要使用 id 时简单地使用。