首页 文章

Reactjs:作为道具访问时未定义的键

提问于
浏览
4

工具:Reactjs 0.14.0 Vanilla Flux

I need unique identifiers for 2 reasons:

所以,假设我有一个如下所示的消息列表:

[
      {
        id: 1241241234,  <-----The unique id is kept here
        authorName:"Nick"
        text:"Hi!"
      },
      ...
]

现在我使用"Array.prototype.map()"在所有者组件 MessageSection 内创建"ownee"组件( MessageListItem

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.

var ConvoListItem = React.createClass({
  render: function() {
    console.log(this.props.key); //Undefined
  }
});

我猜有一个原因是React没有让“关键”用作道具 .

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?

2 回答

  • 10

    最好使用id . 然后在eventHandler中你可以拥有event.target.id .

    function getMessageListItem)(message) {
    
      return (
        <MessageListItem key={message.id} id={message.id} message={message}/>
      );
    }
    
  • 7

    key和ref不是真正的“道具” . 它们通过反应在内部使用,而不是作为道具传递给组件 . 考虑将其作为诸如“id”的道具传递 .

相关问题