Return multiple React elements in a method without a wrapper element

前端 未结 10 970
南方客
南方客 2020-12-16 13:06

I\'m trying to return multiple React elements from a helper method. I could solve it simply by moving around some code, but I\'m wondering if there\'s a cleaner way to solve

10条回答
  •  星月不相逢
    2020-12-16 13:53

    The error message tells you exactly how to solve this:

    Each child in an array or iterator should have a unique "key" prop.

    Instead of this:

    return [
      ' by ',
      {this.props.author},
    ];
    

    Do this:

    return [
       by ,
      {this.props.author},
    ];
    

    Yes, you need to wrap the text node ("by") in a span in order to give it a key. Such are the breaks. As you can see, I've just given each element a static key, since there's nothing dynamic about them. You could just as well use key="1" and key="2" if you wanted.

    Alternatively, you could do this:

    return  by {this.props.author};
    

    ...which obviates the need for keys.

    Here's the former solution in a working snippet:

    const getAuthorUrl = author => `/${author.toLowerCase()}`;
    
    class Foo extends React.Component {
      _renderAuthor() {
        if (!this.props.author) {
          return null;
        }
    
        return [
           by ,
          {this.props.author},
        ];
      }
    
      render() {
        return (
          
    {this.props.datePosted} {this._renderAuthor()}
    ); } } ReactDOM.render(, document.getElementById('container'));
    
    
    

提交回复
热议问题