【发布时间】: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,但也不起作用