Programing

참조에 이벤트 수신기를 추가하는 방법

c10106 2022. 3. 11. 21:53
반응형

참조에 이벤트 수신기를 추가하는 방법

ResactJS 후크 사용법에 이벤트 수신기를 추가하는 방법(버전 16.8. +)

여기 오버플로 오토로 어떤 div의 스크롤 위치를 얻으려고 했던 예가 있다.updateScrollPosition 부름을 받지 않는다.

function Example(props) {
    scroller = useRef();    
    useEffect(() => {
        function updateScrollPosition() {
            // update the scroll position
        }
        if (scroller && scroller.current) {
            scroller.current.addEventListener("scroll", updateScrollPosition, false);
            return function cleanup() {
                 scroller.current.removeEventListener("scroll", updateScrollPosition, false);
            };
        }
    });
    return (
        <div ref={scroller}>
            <div className="overflow-auto">
                some text
            </div>
        </div>
    );
}

나는 너의 도움에 감사한다.

문제는 너의 바깥쪽 div가 스크롤되지 않는다는 거야. 대신 우리 안쪽 div가 스크롤을 할 거야.scroll외부 div에서 이벤트가 트리거되지 않음.내부 칸에 있도록 ref를 변경하면 효과가 있을 것이다.

function Example(props) {
    const scroller = useRef();
 
    useEffect(() => {
        function updateScrollPosition() {
            // update the scroll position
        }

        if (scroller && scroller.current) {
            scroller.current.addEventListener("scroll", updateScrollPosition, false);
            return function cleanup() {
                 scroller.current.removeEventListener("scroll", updateScrollPosition, false);
            };
        }
    }, []);

    return (
        <div>
            <div ref={scroller} className="overflow-auto">
                some text
            </div>
        </div>
    );
}

참조URL: https://stackoverflow.com/questions/58855030/how-to-add-event-listener-to-a-ref

반응형