我创建了一个自定义 Hook ,用于在滚动组件时将元素滚动回 View 。
export const useComponentIntoView = () => {
const ref = useRef();
const {current} = ref;
if (current) {
window.scrollTo(0, current.offsetTop );
}
return ref;
}
现在我在一个功能组件中使用它,比如
<div ref={useComponentIntoView()}>
所以第一次电流总是为空,我知道组件仍然没有安装所以值为 null 。但是我们可以做些什么来始终在我的自定义 Hook 中获取此值,因为仅对于第一次导航,组件滚动不起作用。是否有解决此问题的方法。
最佳答案
我们需要阅读 ref
来自 useEffect
,当它已经被分配。要仅在挂载时调用它,我们传递一个空的依赖项数组:
const MyComponent = props => {
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
window.scrollTo(0, ref.current.offsetTop);
}
}, []);
return <div ref={ref} />;
};
为了让这个功能脱离组件,在它自己的 Hook 中,我们可以这样做:
const useComponentIntoView = () => {
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
window.scrollTo(0, ref.current.offsetTop);
}
}, []);
return ref;
};
const MyComponent = props => {
const ref = useComponentIntoView();
return <div ref={ref} />;
};
我们也可以运行
useEffect
钩子(Hook)经过一定的改变。在这种情况下,我们需要将一个属于状态的变量传递给它的依赖项数组。该变量可以属于同一个组件或祖先组件。例如:const MyComponent = props => {
const [counter, setCounter] = useState(0);
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
window.scrollTo(0, ref.current.offsetTop);
}
}, [counter]);
return (
<div ref={ref}>
<button onClick={() => setCounter(counter => counter + 1)}>
Click me
</button>
</div>
);
};
在上面的示例中,每次单击按钮时都会更新计数器状态。此更新会触发新的渲染,并且由于自上次
useEffect
以来计数器值发生了变化被调用,它运行 useEffect
打回来。
关于reactjs - React 自定义 Hook 使用 useRef 在第一次调用组件加载时返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59000716/