从子项访问父引用以进行帧器运动useElementScroll



我有以下两个组件:

应用程序.tsx

import { useRef, VFC } from "react";
import Card from "./Card";
const App: VFC = () => {
const scrollRef = useRef<HTMLDivElement>(null);
return (
<div ref={scrollRef}>
<Card scrollRef={scrollRef} />
</div>
);
};
export default App;

卡.tsx

import { useElementScroll } from "framer-motion";
import { FC, RefObject } from "react";
interface CardProps {
scrollRef: RefObject<HTMLElement>;
}
const Card: FC<CardProps> = ({ scrollRef }) => {
const { scrollY } = useElementScroll(scrollRef);
console.log(scrollY);
return null;
};
export default Card;

卡组件现在抛出以下错误:

ref provided to useScroll must be passed into a HTML element.

我的示例与Framer Motion文档中的示例之间的唯一区别是,我从父组件而不是子组件获取引用。我不明白它犯了什么错误。有人能帮忙解释一下吗?

这里的实例:

https://codesandbox.io/s/framer-motion-scroll-ref-p3bqq

只需在scrollRef元素实际存在的父组件内部使用useElementScroll()挂钩。

然后,不将scrollRef传递到子组件中,而是从useElementScroll()传递必要的值,在您的情况下,它将是scrollY

这对我有效。

最新更新