首页 > 解决方案 > 如何在 React 中创建组件的 props.children 元素的索引数组

问题描述

我正在尝试构建一个轮播应用程序,您可以在其中将轮播项目作为轮播组件的子项。

   return (
    <div className="carousel-container" style={{width: containerWidth}}>
    <button className="button-left" >L</button>
    <button className="button-right" >R</button>
    <div className="carousel-slider" style={{
        display: "flex",
        flexDirection: "row",
         flexWrap: "none",
      overflow: "scroll",
     alignItems: "center",
    height: props.height, 
    width: "100%", 
    }}>
        {props.children}
    </div>
    </div>
)

我希望能够将此轮播滚动到选定的孩子。我认为我应该这样做的方式是让 button-left 和 button-right 元素滚动到下一个/上一个孩子的索引。但是,我无法让孩子的索引告诉应用滚动到某个孩子。

有谁知道我获取“carousel-slider”的 props.children 索引的方法,将它们放在一个数组中,然后按下左/右按钮滚动到相应的孩子?孩子是 HTML emenets,如 div 或 imges。

Codesandbox:https ://codesandbox.io/s/hardcore-goodall-usspz?file=/src/App.js

PS 我知道那里有非常酷的轮播插件。我这样做是为了在 React 上做得更好。

标签: javascriptreactjscarouselreact-props

解决方案


您可以使用React.Children.toArraychildren道具变成一组孩子。从文档:

以平面数组的形式返回children不透明数据结构,每个子元素都分配有键。如果你想在你的渲染方法中操作子元素的集合,特别是如果你想重新排序或slice this.props.children在传递它之前,它很有用。

一旦你有了一个数组,你就可以对数组使用索引。


推荐阅读