我不能使用"element.style.top = window.scrollY"移动元素吗?



我正在尝试制作某种浮动输入元素,使其跟随滚动。最后我成功了,下面有代码。

我想知道的是,如果我改变";setText(window.rollY(";至";document.querySelector(".code(.style.top=window.sollyY";它并没有给我同样的结果。我认为这是相同的代码,但后来的代码不起作用。有人能告诉我为什么吗?谢谢

import React, { useState } from "react";
function Input() {
const [scroll, setScroll] = useState(0);

window.addEventListener(
"scroll",
function () {
if (typeof document.querySelector(".code") === "undefined") {
alert("TT");
} else {
setScroll(window.scrollY);              // *this part
}
},
{ passive: true }
);
return (
<input
style={{
top: text
}}
className="code"
autoComplete="on"
placeholder="Write code please"
/>
);
}
export default Input;
setScroll(window.scrollY+"px");  

使用useRef()钩子而不是document.querySelector(".code")。React使用虚拟DOM,因此当document.querySelector(".code")运行时,rea DOM还不可用。但是您可以使用useRef来获取虚拟DOM并对其执行操作。您可以使用ref的.current属性访问元素。

其次,滚动事件处理程序需要封装在React的useEffect钩子中,以确保在组件安装时添加它。

最新更新