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'.

  • 相关阅读:
    什么叫套接字
    浅谈labviEW定时器
    C#线程篇---Task(任务)和线程池不得不说的秘密
    async与await详解
    异步编程与多线程的联系与区别
    什么是Task
    MVC模式的介绍(C#)
    Git指令
    Redis安装部署、Jedis的使用
    Oracle——序列、索引、同义词
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13355327.html
Copyright © 2011-2022 走看看