将 useRef 传递给自定义钩子的方法是什么?我正在创建一个自定义钩子以在用户到达带有 react-intersection-observer 的部分时触发动画,并且如果用户通过多个,则动画不会再次发生。
如果我像这样传递参考:useAnimation 参数:const useAnimation = (customRef)
和来自 react-intersection-observer 的 setView 方法,如下所示:const { ref: customRef, inView: elementIsVisible } = useInView();
我得到Parsing error: Identifier 'customRef' has already been declared.
如果我删除参考:它会发生同样的事情。
如果我 console.log 我得到的 customRef 参数current: undefined
这是完整的代码:useAnimation:
import React, { useEffect, useState, useRef, useContext } from "react";
import { DisableAnimationContext } from "../context/disableAnimationContext";
import { useInView } from "react-intersection-observer";
const useAnimation = (customRef) => {
const { setdisableAnimation } = useContext(DisableAnimationContext);
const { ref: customRef, inView: elementIsVisible } = useInView();
const [animationHappened, setAnimationHappened] = useState(false);
const [animationCounter, setAnimationCounter] = useState({
counter: 0,
});
useEffect(() => {
if (elementIsVisible) {
setdisableAnimation(true);
var currentState = animationCounter.counter;
setAnimationCounter({
...animationCounter,
counter: (currentState += 1),
});
}
if (animationCounter.counter > 0) {
setAnimationHappened(true);
}
}, [elementIsVisible]);
return { elementIsVisible, animationHappened };
};
export default useAnimation;
这是我在组件中调用自定义挂钩的方式:
import React, { useRef, useContext } from "react";
import useAnimation from "../../../hooks/useAnimation";
const aboutRef = useRef();
console.log(aboutRef);
const { elementIsVisible, animationHappened } = useAnimation(aboutRef);