[英]I am using UseEffect Hook, but still component is getting Uncaught TypeError: Cannot set properties of null. in react
I have to give a hover effect to a certain element that has an id "address-instructions".我必须为具有 id“地址指令”的某个元素提供 hover 效果。 I have used UseEffect so that it is only accessed after being rendered, but I still get Uncaught TypeError: Cannot set properties of null (setting 'onmouseover'), which indicates that the component is not rendering.
我使用了 UseEffect 以便仅在渲染后访问它,但我仍然收到 Uncaught TypeError: Cannot set properties of null (setting 'onmouseover'),这表明组件未渲染。 Please help.
请帮忙。 Thank you in advance.
先感谢您。
useEffect(()=>{
document.getElementById("address-i").onmouseover = () => {
document.getElementById("address-instructions").style.display = "block";
};
document.getElementById("address-i").onmouseout = () => {
document.getElementById("address-instructions").style.display = "none";
};
}, []);
you can use useRef for the same...您可以将useRef用于相同的...
import "./styles.css";
import { useRef } from "react";
export default function App() {
const h2 = useRef();
const hideElement = (ref) => {
ref.current.style.display = "none";
};
const visibleElement = (ref) => {
ref.current.style.display = "block";
};
return (
<div className="App">
<h1
onMouseOver={hideElement.bind(this, h2)}
onMouseOut={visibleElement.bind(this, h2)}
>
Hello CodeSandbox
</h1>
<h2 ref={h2}>Start editing to see some magic happen!</h2>
</div>
);
}
You can use above code directly on codesandbox .您可以直接在codesandbox上使用上面的代码。
I hope this will help you!我希望这能帮到您! Happy coding...
快乐的编码...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.