0

我必须为项目列表实现水平滚动,但使用后退和前进箭头按钮。以下是我实现的,但我想知道是否有另一种最好的方法来做到这一点,可能是使用 REFS。

  const scrollLeft = () => {
     let scrollPosition = document.getElementById('buttonRow')?.scrollLeft;
     if (scrollPosition) {
     scrollPosition = scrollPosition - 80;
     document.getElementById('buttonRow')?.scroll({ left: scrollPosition, behavior: 'smooth' 
      });
    }
  };

const scrollRight = () => {
  let scrollPosition = document.getElementById('buttonRow')?.scrollLeft;
  if (scrollPosition || scrollPosition === 0) {
  scrollPosition = scrollPosition + 80;
  document
    .getElementById('buttonRow')
    ?.scroll({ left: scrollPosition, behavior: 'smooth' });
  }
};
#Pivots types are array i am using, which i want to display.
let PivotTypes = ['item1', 'item2', 'item3', 'item4']

这是我的 jsx

        <LeftArrowButton onClick={() => scrollLeft()}>
          <StyledLeftArrow />
        </LeftArrowButton>
        <InlineContainer>
          <ButtonRow id="buttonRow">
            {PivotTypes.map(pivotType => {
              return (
                <PivotButton
                  style={{
                    backgroundColor: activePivots.some(
                      pivot => pivot === pivotType
                    )
                      ? '#00a1de'
                      : '#8b8b8b',
                  }}
                  id={pivotType + 'PivotButton'}
                >
                  {pivotType}
                </PivotButton>
              );
            })}
          </ButtonRow>
        </InlineContainer>
        <RightArrowButton onClick={() => scrollRight()}>
          <StyledRightArrow />
        </RightArrowButton>

这可行,但我对实现不满意,因为它有 getElementById,我觉得这不是反应方式:/

注意:对于 ui,我使用的是 @material-ui/core 包

UI是这样的 在此处输入图像描述

**任何建议/反馈将不胜感激。

4

1 回答 1

0

如果我理解正确,您只想向您的 html 标签添加水平滚动。

为此,您可以使用 css。

overflow-x:scroll;

于 2020-07-10T07:52:28.517 回答