【发布时间】:2022-01-10 03:00:10
【问题描述】:
当我想将 ref 添加到主元素时,会出现以下错误。
错误
Type 'number | MutableRefObject<any>' is not assignable to type 'LegacyRef<HTMLElement>'.
Type 'number' is not assignable to type 'LegacyRef<HTMLElement>'
如何解决?
index.tsx
import React from "react";
import ReactDOM from "react-dom";
import useScrollPercentage from "./useScrollPercentage";
// reset styles
Object.assign(document.body.style, {
overflow: "hidden",
margin: "0"
});
function App() {
const [scrollRef, scrollPercentage] = useScrollPercentage();
return (
// attach scrollRef to scroll container
<main ref={scrollRef} style={{ height: "100vh", overflowY: "scroll" }}>
{/* Simulate overflowing content */}
<div style={{ height: 3000 }} />
{/* Display scroll percentage */}
<h1 style={{ position: "fixed", top: 10, left: 10 }}>
{`${scrollPercentage}%`}
</h1>
</main>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
useScrollPercentage.js
import { useRef, useState, useEffect } from "react";
export default function useScrollPercentage() {
const scrollRef = useRef(null);
const [scrollPercentage, setScrollPercentage] = useState(NaN);
const reportScroll = e => {
setScrollPercentage(getScrollPercentage(e.target));
};
useEffect(
() => {
const node = scrollRef.current;
if (node !== null) {
node.addEventListener("scroll", reportScroll, { passive: true });
if (Number.isNaN(scrollPercentage)) {
setScrollPercentage(getScrollPercentage(node));
}
}
return () => {
if (node !== null) {
node.removeEventListener("scroll", reportScroll);
}
};
},
[scrollPercentage]
);
return [scrollRef, Number.isNaN(scrollPercentage) ? 0 : scrollPercentage];
}
function getScrollPercentage(element) {
if (element === null) {
return NaN;
}
const height = element.scrollHeight - element.clientHeight;
return Math.round((element.scrollTop / height) * 100);
}
代码沙盒
https://codesandbox.io/s/scroll-percentage-hook-forked-6bcyw?file=/src/index.tsx
【问题讨论】:
标签: reactjs typescript