React.js:作为prop进行访问时未定义键 [英] Reactjs: Key undefined when accessed as a prop
问题描述
工具:Reactjs 0.14.0 Vanilla Flux
Tools: Reactjs 0.14.0 Vanilla Flux
出于以下两个原因,我需要唯一标识符:
- Child Reconciliation
- Keeping track of what child was clicked
所以说我有一个看起来像这样的消息列表:
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!"
},
...
]
现在我使用"Array.prototype.map()"创建
And now I use a "Array.prototype.map()" to create "ownee" component(MessageListItem
) inside of the owner component 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>
}
});
但是this.props.key在MessageListItem中是未定义的,即使我知道在传递时已定义的事实.
var ConvoListItem = React.createClass({
render: function() {
console.log(this.props.key); //Undefined
}
});
我猜有一个原因,就是React不让键"用作道具.
I'm guessing there is a reason that React is not letting "key" to be used as a prop.
问题:
如果我不能使用key作为道具-那么处理在包含状态的子元素的动态列表上进行keying和设置唯一标识符的双重性的正确方法是什么?
推荐答案
最好使用id.然后在eventHandler中可以拥有event.target.id.
It is best to use id. Then in the eventHandler you can have event.target.id.
function getMessageListItem(message) {
return (
<MessageListItem key={message.id} id={message.id} message={message}/>
);
}
这篇关于React.js:作为prop进行访问时未定义键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!