React JSX条件包装器用于引导网格

Pet*_*ton 4 twitter-bootstrap reactjs react-jsx

在使用Bootstrap网格渲染React组件时面对这个有趣的事情,假设我需要col-md-6在a中渲染两个row,每个<Book />组件都放在一个col-md-6 div块中

+---------------------+
| col-md-6 | col-md-6 |
| Book     | Book     |  <--- row
|---------------------|
| col-md-6 | col-md-6 |
| Book     | Book     |  <--- row
+---------------------+
Run Code Online (Sandbox Code Playgroud)

它预计形成类似于以下结构,

<Row>
    <Col>
        <Book />
    </Col>
    <Col>
        <Book />
    </Col>
</Row>
<Row>
    <Col>
        <Book />
    </Col>
    <Col>
        <Book />
    </Col>
</Row>
Run Code Online (Sandbox Code Playgroud)

我尝试渲染如下,

export default class BookList extends React.Component {
    render() {
        let books = [];
        lodash.each(this.props.books, function (book, index) {
            index % 2 === 0 ? books.push(<div className="row" key={index}>): null;
            books.push(
                    <div className="col-md-6">
                        <Book />
                    </div>
            )
            index % 2 === 1 || index === this.props.books.length - 1? books.push(</div>): null
        })

        return (
            <div className="container">
                {books}
            </div>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

但输出是格式错误的HTML,看起来JSX验证渲染上的每个项目,而不是等待关闭标记.

是否有任何方法或提示使其正常工作?

Ori*_*ori 6

您已经将JSX视为字符串而不是XML,当它被编译为JS时,它是无效的.

React适用于小组件,因此将BooksContainer分成几组并呈现BooksRows,BooksRows将呈现书籍(小提琴 - 检查结果):

码:

const Book = ({ book }) => (
  <div className="col-md-6">
    { book.name }
  </div>
);

const BooksRow = ({ bookPair }) => (
  <div className="row">
    {
      bookPair.map((book, index) => (
        <Book key={ index } book={ book }/>
      ))
    }
  </div>
);

const BooksContainer = ({ books }) => (
  <div className="container">
    {
      books.reduce((pairs, book, index) => { // split the books into pairs
        if(index % 2 === 0) {
           pairs.push([]);
        }
        pairs[pairs.length - 1].push(book);
        return pairs;
      }, []).map((pair, index) => ( // map the pairs to row
        <BooksRow key={ index } bookPair={ pair } />
      ))
    }
  </div>
);

const books = [
  {
    name: 'cats'
  },
  {
    name: 'dogs'
  },
  {
    name: 'rabbits'
  },
  {
    name: 'elephents'
  },
  {
    name: 'snails'
  },
  {
    name: 'tigers'
  }
];

ReactDOM.render(
  <BooksContainer books={ books } />,
  document.getElementById('container')
);
Run Code Online (Sandbox Code Playgroud)