zoukankan      html  css  js  c++  java
  • [React] useImperativeHandle + forwardRef

    We have a message app:

    function App() {
        const messageDisplayRef = React.useRef()
        ....
        const scrollToTop = () => messageDisplayRef.current.scrollToTop()
        const scrollToBottom = () => messageDisplayRef.current.scrollToBottom()
    
        return (
            <div className="messaging-app">
                <button onClick={scrollToTop}>scroll to top</button>
                <Messages ref={messageDisplayRef}... />
                <button onClick={scrollToBottom}>scroll to bottom</button>
            </div>
        )
    }

    The idea is we want to control scrolling to top or bottom by two buttons from App. We pass the 'ref' from App to Messages component.

    function Messages(props, ref) {
        React.useLayoutEffect(() => {
            scrollToBottom()
        })
    
        function scrollToTop() { containerRef.current.scrollTop = 0 }
        function scrollToBottom() {containerRef.current.scrollTop = containerRef.current.scrollHeight}
    
        React.useImperativeHandle(ref, () => ({
            scrollToTop,
            scrollToBottom
        }))
    
        return (
            <div ref={containerRef}...>
                  ...
            </div>
        )
    }
    Messages = React.forwardRef(Messages)

    Since we use 'forwardRef' for Messages component, so that it can receive a 'ref' params.

    We use 'useImperativeHandle' to expose the 'scrollToTop' & 'scrollToBottom' APIs to parent component though 'ref'.

  • 相关阅读:
    luogu_P3195 [HNOI2008]玩具装箱TOY
    CF_837D
    luogu_P3584 [POI2015]LAS
    大一下存活纪实
    Mathematical Logic for Computer Science 读书笔记
    集训补题合集
    图论笔记4 平面图与可平面图
    软件分析笔记3 DFA
    软件分析笔记2 IR
    软件分析笔记1 Intro
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13355327.html
Copyright © 2011-2022 走看看