【问题标题】:React Carousel with Multiple ItemsReact Carousel 与多个项目
【发布时间】:2019-02-24 17:03:00
【问题描述】:

我的滑块在三元条件下出现问题,我该如何解决? 它认为我在最后一个子句完成之前关闭了该项目。这是构建多项目轮播的尝试。

<Carousel className="col-md-7 col-11" indicators="true" controls="false">
    {this.props.children.map((rooms,index) => 
        (index === 0 || index % 3 === 0) ? <Carousel.Item><h1>First</h1> : 
            ((index+1) % 3 === 0) ? <h1>Last</h1></Carousel.Item> : <h1>Middle</h1>
        )
    }
</Carousel>

【问题讨论】:

标签: reactjs carousel ternary-operator react-bootstrap


【解决方案1】:

问题是这不是有效的 JSX。

您不能将没有结束标记的开始&lt;Carousel.Item&gt; 标记呈现为同一表达式的一部分。很清楚您在这里尝试做什么,但它无法工作,因为 JSX 编译器无法“知道”结束标记 ever 会被渲染,因为这取决于children。您必须将开始和结束标记呈现为同一表达式的一部分,以便 JSX 编译。

可能最简洁的方法是将children 分组到一个单独的函数中,然后映射结果,只需在&lt;Carousel.Item&gt;&lt;/Carousel.Item&gt; 中渲染每个组,如下所示:

function groupIntoThrees (children) {
  const output = []
  let currentGroup = []

  children.forEach((child, index) => {
    currentGroup.push(child)

    if (index % 3 === 2) {
      output.push(currentGroup)
      currentGroup = []
    }
  })

  return output
}

... later in render method ...

<Carousel className="col-md-7 col-11" indicators="true" controls="false">
  {groupIntoThrees(this.props.children).map((group) => (
    <Carousel.Item>
      <h1>first: {group[0]}</h1>
      <h1>middle: {group[1]}</h1>
      <h1>last: {group[2]}</h1>
    </Carousel.Item>
  )} 
</Carousel>

【讨论】:

  • 但是我是在地图里面做的,这就是问题所在。我必须知道打开和关闭项目的第一个和最后一个是什么。我正在尝试构建一个多项目轮播。
  • 我必须在同一个轮播项目中放置 3 个

    标签。

  • 在那个例子中,如果我有超过 3 个

    它将继续在同一个项目中呈现。

  • @AndréGonçalves 啊,今天回头看了一眼,现在我知道你想做什么了。所以是的,问题是你不能像你想要的那样做,在一个表达式中渲染一个开始标签,然后在另一个表达式中关闭它,在两者之间渲染其他东西。您必须首先对子项进行分组,然后在每个项目中一次将它们全部渲染,并在同一表达式中使用开始和结束标记。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 2021-12-05
  • 1970-01-01
  • 2022-11-26
  • 2020-01-11
  • 2021-08-09
  • 1970-01-01
相关资源
最近更新 更多