我正在尝试为项目的水平滚动部分实现 POC。我在水平滚动部分上方有 3 个彼此相邻的 h3,这些 h3 应该对应于水平位中的各个子部分。
我正在使用 react-intersection-observer 创建子部分的引用,以便在用户单击其中一个 h3 时能够滚动到它们。状态设置正确,在 React Dev Tools 中,我可以看到 useInView 钩子设置正确,并将 s 显示为 refs。但是,当我尝试在任何地方访问 refOne.current 时,它会返回未定义。我在这里明确使用 useLayoutEffect 来等待所有 DOM 节点被完全绘制,但 refOne.current 仍然是未定义的。
import React, { useState, useLayoutEffect } from 'react';
import { useInView } from 'react-intersection-observer';
import classNames from 'classnames';
import classes from './Projects.module.css';
const Projects = () => {
const [activeState, setActiveState] = useState('one');
let [refOne, inViewOne, entryOne] = useInView({
threshold: 1,
});
let [refTwo, inViewTwo, entryTwo] = useInView({
threshold: 1,
});
let [refThree, inViewThree, entryThree] = useInView({
threshold: 1,
});
useLayoutEffect(() => {
console.log(refOne.current) // comes back undefined
checkAndScroll(activeState);
}, [activeState]);
const setActiveHeading = (id) => {
setActiveState(id);
};
let oneClasses = classNames(classes.heading, {
[classes.activeHeading]: activeState === 'one',
});
let twoClasses = classNames(classes.heading, {
[classes.activeHeading]: activeState === 'two',
});
let threeClasses = classNames(classes.heading, {
[classes.activeHeading]: activeState === 'three',
});
const checkAndScroll = (id) => {
console.log(refOne.current) // comes back undefined
if (id === 'one' && !inViewOne) {
scrollToRef(refOne);
} else if (id === 'two' && !inViewTwo) {
scrollToRef(refTwo);
} else if (id === 'three' && !inViewThree) {
scrollToRef(refThree);
}
};
const scrollToRef = (ref) => {
console.log(refOne.current) // comes back undefined
if (ref && ref.current) {
ref.current.scrollIntoView();
}
};
return (
<>
<div className={classes.headingsContainer}>
<h3
className={oneClasses}
id={classes.headingOne}
onClick={() => setActiveHeading('one')}
>
One
</h3>
<h3
className={twoClasses}
id={classes.headingTwo}
onClick={() => setActiveHeading('two')}
>
Two
</h3>
<h3
className={threeClasses}
id={classes.headingThree}
onClick={() => setActiveHeading('three')}
>
Three
</h3>
</div>
<div className={classes.container}>
<div ref={refOne} className={classes.one} />
<div ref={refTwo} className={classes.two} />
<div ref={refThree} className={classes.three} />
</div>
</>
);
};
export default Projects;
我已经为此工作了几个小时,但我已经无能为力了。任何帮助深表感谢!