Return multiple React elements in a method without a wrapper element

前端 未结 10 939
南方客
南方客 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:35

    I like to have an If-component around for such things, and I have wrapped everything into a span, as it doesn't really break anything and makes the need for keys go away...

    const getAuthorUrl = author => `/${author.toLowerCase()}`;
    
    function If({condition,children}) {
      return condition ? React.Children.only(children) : null;
    
    }
    
    class Foo extends React.Component {
    
      render() {
        return (
          
    {this.props.datePosted} by {this.props.author}
    ); } } ReactDOM.render(, document.getElementById('container'));
    
    
    

    ...skipping the array thing altogether?

提交回复
热议问题