【问题标题】:How do I set a default scroll position for a component without scrolling the entire page in React?如何在不滚动 React 中的整个页面的情况下为组件设置默认滚动位置?
【发布时间】:2023-02-05 11:15:36
【问题描述】:

我有一个必须可滚动的父页面。我有一个日历视图,该页面也可以滚动。但是,我不希望日历呈现并且默认情况下视图在顶部显示凌晨 1 点。我希望它向下滚动大约一半,用户可以在它自己的组件中向上或向下滚动。但是,我为解决此问题所做的所有尝试也会滚动父页面。我认为正在发生的事情是滚动父页面,当它不能再滚动时,它将组件滚动到我想要的位置。有什么方法可以在不滚动父组件的情况下做到这一点?

我尝试了 refs 但每次我这样做时父组件都会滚动

这是我试过的代码

export default function WeeklyCalendar({classes, clinicals, blockedTime, fileClinicalList}) {
  const calendarRef = useRef(null);

  useEffect(() => {
    calendarRef.current.scrollTo(0, 500);
  }, []);


  return (
    <div>
        <div
          style={{
            position: 'sticky',
            zIndex: '10',
            backgroundColor: PlatformStyles.LogoNavyBlue,
            width: '100%',
            top: '0px',
            left: '-10%',
            right: '50px',
            fontWeight: 'bold'
          }}
          >
          {days.map((day , index) => {
            let width = columnWidth
            if (index === 0) {
              width = '5%'
            }
            return (
              <div
              style={{
                position: '',
                display: 'inline-block',
                zIndex: 11,
                color: 'white'
                width,
                textAlign: 'center'
              }}
              >
              {day}    
            </div>
            )
            
          })}
        </div>
    <div
      ref={calendarRef}
      style={{
        scrollMarginTop: '1000px',
        height: '700px',
        position: 'relative', 
        marginLeft: '40px'
      }}
      >
        {hours.map((hour) => {

          let id = hour
          if (hour === 6) {
            id = 'scrollId'
          }

          return (
            <div
            key={hour}
            id={id}
            style={{
              position: 'absolute',
              top: `${(hour - 0.5) * multiplier + .51}%`,
              bottom: `${100 - (hour + 1) * multiplier}%`,
              left: '-2%',
              right: '0%',
              fontSize: '11px',
              textAlign: 'left',
              fontWeight: 'bold',
              alignItems: 'center'
            }}
          >
            {convertTime(hour)}
          </div>
          )
          
        })}
        
        {/* Adds line in the middle of the hour */}
        {hours.map((hour) => 
          <div
            key={hour}
            style={{
              position: 'absolute',
              top: `${hour * multiplier}%`,
              bottom: `${100 - (hour + 1) * multiplier}%`,
              left: '.5%',
              right: '0%',
              marginLeft: '22px',
              borderBottom: '1px solid lightgray',
              textAlign: 'left',
              fontWeight: 'bold',
              alignItems: 'center'
            }}
          >
          </div>
        )}
        {events.map((event, index) => 
          event.day.map((day) => 
          <Event
            key={`event-${index}-${day}`}
            event={event}
            day={day}
            />
          )
        )}
    </div>
    </div>
  )
}

【问题讨论】:

  • 你能分享一下你试过的代码吗?通过使用 ref 并执行 ref.current.scrollTop = ref.current.scrollHeight / 2 - (ref.current.offsetHeight / 2),您应该能够在不影响父页面的情况下设置默认滚动位置。
  • 我用我拥有的代码编辑了帖子。我也试过围绕主 div 的 ref,但也不起作用

标签: css reactjs scroll


【解决方案1】:

以下内容应生成一个初始滚动高度为其滚动长度一半(减去其高度的一半)的组件。

  const ChildComponent = () => {
     const ref = useRef(null);

     useEffect(() => {
        if (ref.current){
           const elHeight = ref.current.offsetHeight / 2;
           ref.current.scrollTop = ref.current.scrollHeight / 2 - elHeight;
        }
     }, [ref.current]);

     return <div ref={ref}>...</div>
  }

如果你不希望它成为一半滚动高度,你也可以静态设置它:

  const ChildComponent = () => {
     const ref = useRef(null);

     useEffect(() => {
        if (ref.current){
           ref.current.scrollTop = 200; // px
        }
     }, [ref.current]);

     return <div ref={ref}>...</div>
  }

示例:https://codesandbox.io/s/distracted-keldysh-03x0v5?file=/src/App.tsx

【讨论】:

  • 这是我到处都发现的,从逻辑上讲它应该有效,但无论出于何种原因,我似乎无法让它发生
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多