相邻的 JSX 元素必须包装在带有引导列的封闭标记中



我正在使用 React Bootstrap 并尝试遍历两个单独列中的内容,如下所示:

  <Container>
    <Row>
      {this.state.products.map(product => (
      <Col md={8}>
        <div className="title">{product.name}</div>
        <div className="desc">{product.description}</div>
      </Col>
      <Col md={4}>
        <div className="price">{product.price}</div>
      </Col>
      ))}
    </Row>
  </Container>

我有我的结束标签,所以不确定为什么会出现错误?

映射的返回也需要包装在包含标签中,可以使用 React 片段标签<> https://reactjs.org/docs/fragments.html#short-syntax

<Container>
    <Row>
      {this.state.products.map(product => (
         <>
           <Col md={8}>
              <div className="title">{product.name}</div>
              <div className="desc">{product.description}</div>
           </Col>
          <Col md={4}>
            <div className="price">{product.price}</div>
          </Col>
      </>
      ))}
    </Row>
  </Container>

试试这个:

问题是,您对产品Array map返回两个类型 Col 的组件,而 React 只接受一个返回的元素。

在这里解释。

此外,<React.Fragment></React.Fragmint>组件包装器也可以使用以下语法编写:<></>

  <Container>
    <Row>
      {this.state.products.map(product => (
        <React.Fragment>
          <Col md={8}>
            <div className="title">{product.name}</div>
            <div className="desc">{product.description}</div>
          </Col>
          <Col md={4}>
            <div className="price">{product.price}</div>
          </Col>
        </React.Fragment>
      ))}
    </Row>
  </Container>

最新更新