reactjs - Framer 运动根据其他元素偏移为 x 设置动画
问题描述
我使用“react-tabs”中的选项卡创建了一个页面,我想使用成帧器动作自动滚动到右侧选项卡。这是我想出的
const HotelModal = ({ hotel }) => {
const constraintsRef = useRef(null);
const vw = () => {
// Gets size of one vw for animations
return (
(window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth) / 100
);
};
return (
<ModalContext.Consumer>
{(context) => {
if (context.showModal) {
return (
<StyledContainer>
<StyledHeader>
<FontAwesomeIcon
icon={faArrowLeft}
color={colors.white}
onClick={context.toggleModal}
/>
<h2>{hotel.title}</h2>
</StyledHeader>
<Tabs
selectedIndex={context.modalTabIndex}
onSelect={(index) => context.setModalTabIndex(index)}
>
<StyledListContainer ref={constraintsRef}>
<StyledTabList
style={{ width: (hotel.variants.length + 2) * 60 + "vw" }}
as={motion.ul}
initial={{ x: 0 }}
animate={{
x: -50 * context.modalTabIndex * vw(),
}}
transition={{ ease: "easeOut", duration: 0.5 }}
drag="x"
dragConstraints={constraintsRef}
>
<StyledTab>Description</StyledTab>
<StyledTab>Équipements et Services</StyledTab>
{hotel.variants.map((room, i) => (
<StyledTab key={i}>{room.attributes.room}</StyledTab>
))}
</StyledTabList>
</StyledListContainer>
<TabPanel className="tabPanel">
<HotelShortDescription hotel={hotel} />
</TabPanel>
<TabPanel className="tabPanel">
<HotelEquipments hotel={hotel} />
</TabPanel>
{hotel.variants.map((room, i) => (
<TabPanel key={i} className="tabPanel">
<StyledDetailsContainer>
<h3>{room.attributes.room}</h3>
<p>{room.description}</p>
<h3>Room Amenities</h3>
<StyledAmenitiesList>
{room.amenities.map((amenity, i) => (
<li key={i}>
<FontAwesomeIcon
icon={faChevronRight}
style={{ fontSize: "0.8em" }}
/>
<span>{amenity}</span>
</li>
))}
</StyledAmenitiesList>
</StyledDetailsContainer>
</TabPanel>
))}
</Tabs>
</StyledContainer>
);
}
return null;
}}
</ModalContext.Consumer>
);
};
在我的 StyledTabList 中,我想根据 context.modalTabIndex 滚动到 x = 到右侧元素的 offsetLeft。不幸的是,我不确定如何在触发动画之前获得这些偏移量。
我尝试使用一个简单的 document.getElementsByClass 但它不起作用,因为每个 TabPanel 都是在之后创建的。我还尝试将每个 TabPanel 放在 ref 数组中,但问题相同。