具有多个项目的React Carousel

问题描述 投票:0回答:1

我的滑块具有三元条件时遇到问题,我该如何解决?它认为我在最后一个条款完成之前关闭了该项目。这是尝试构建多项旋转木马。

<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个回答
0
投票

问题是这不是有效的JSX。

如果没有结束标记作为同一表达式的一部分,则无法呈现打开的<Carousel.Item>标记。很清楚你在这里尝试做什么,但它无法工作,因为JSX编译器无法“知道”将关闭标记,因为这取决于children。您必须将开始和结束标记作为同一表达式的一部分进行渲染,以便JSX进行编译。

可能最干净的事情是在单独的函数中对children进行分组,然后映射结果,只需在<Carousel.Item></Carousel.Item>中渲染每个组,如下所示:

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>
© www.soinside.com 2019 - 2024. All rights reserved.