useref 无法在 react comp 中设置属性'display'



嘿,我正在尝试制作一个基本的React滚动到顶部按钮,我从w3得到了这段代码,我认为这很好。我试图更改一些东西,但没有成功,我认为解决方案很愚蠢。希望得到帮助,谢谢。我得到这个错误:

无法设置未定义的属性"display">

这是我的代码:

import React, { useRef } from "react";
const ScrollToTop = () => {
const myButton = useRef(null);
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (
document.body.scrollTop > 20 ||
document.documentElement.scrollTop > 20
) {
myButton.style.display = "block";
} else {
myButton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
return (
<div>
<button onclick="topFunction()" ref={myButton} title="Go to top">
Top
</button>
</div>
);
};
export default ScrollToTop;

应为myButton.current.style.display.

无论何时使用useRef,都需要在变量名后面添加current属性它将与myButton.current.style.display一起工作。按钮样式固定在底部,它将工作

最新更新