Hook - useScroll
import React, { useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const useScroll = () => {
const [state, setState] = useState({ x: 0, y: 0 });
const onScroll = () => {
setState({ x: window.scroolX, y: window.scrollY });
};
useEffect(() => {
window.addEventListener("scroll", onScroll);
return () => {
window.removeEventListener("scroll", onScroll);
};
}, []);
return state;
};
const App = () => {
const { y } = useScroll();
return (
<div className="App" style={{ height: "1000vh" }}>
<h1
style={{
left: 0,
right: 0,
position: "fixed",
color: y > 100 ? "red" : "blue"
}}
>
{" "}
RED ? BLUE ?{" "}
</h1>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Reference
この問題について(Hook - useScroll), 我々は、より多くの情報をここで見つけました https://velog.io/@wonjongseo/Hook-useScrollテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol