我有一个列表,使用 material-ui 构建。里面有很多项目,所以滚动条是可见的。
我想做的是滚动到所选项目。对如何实现这一点有任何想法吗?
单击项目列表后应如下所示(所选项目位于中心):
保持对List的引用,然后单击ListItem,根据以下内容计算需要滚动的量:
可见列表项的数量。
const scrollableListRef = React.createRef();
function Row(props) {
const { index, style } = props;
const placeSelectedItemInTheMiddle = (index) => {
const LIST_ITEM_HEIGHT = 46;
const NUM_OF_VISIBLE_LIST_ITEMS = 9;
const amountToScroll = LIST_ITEM_HEIGHT * (index - (NUM_OF_VISIBLE_LIST_ITEMS / 2) + 1) ;
scrollableListRef.current.scrollTo(amountToScroll, 0);
}
return (
<ListItem button style={style} key={index}
onClick={() => {placeSelectedItemInTheMiddle(index)}}>
<ListItemText primary={`Item ${index + 1}`} />
</ListItem>
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句