javascript - 如何在 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 上做得更好。
解决方案
您可以使用React.Children.toArray
将children
道具变成一组孩子。从文档:
以平面数组的形式返回
children
不透明数据结构,每个子元素都分配有键。如果你想在你的渲染方法中操作子元素的集合,特别是如果你想重新排序或slice
this.props.children
在传递它之前,它很有用。
一旦你有了一个数组,你就可以对数组使用索引。
推荐阅读
- r - 如何在R中选择一系列列
- python - Django(Python) 注册无法正常工作
- angular - *ngFor Bootstrap 中的宽度内容变量
- excel - 如果 PowerPivot Dax 中月份的值为空,如何显示运行总计?
- java - ObjectWriter 的 withoutAttribute 方法不起作用
- powershell - 匹配 CSV 中的列并导出具有唯一值的 CSV
- python - Tkinter Entry 小部件不适用于 .get() 函数
- c# - 如何加快从串行端口(RS422)的读取速度?
- algorithm - 动态问题中的重叠子问题(硬币找零问题)
- machine-learning - 如何随机打乱 Pytorch 数据集的标签?