React.js:作为prop进行访问时未定义键 [英] Reactjs: Key undefined when accessed as a prop

查看:63
本文介绍了React.js:作为prop进行访问时未定义键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

工具:Reactjs 0.14.0 Vanilla Flux

Tools: Reactjs 0.14.0 Vanilla Flux

出于以下两个原因,我需要唯一标识符:

  1. 子对帐
  2. 跟踪单击了哪个孩子
  1. Child Reconciliation
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆