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

  • 相关阅读:
    科技公司网站
    jquery 设置元素内容html(),text(),val()
    jquery 相关class属性的操作
    jquery attr()和prop()方法的使用
    检测移动设备横竖屏
    设定程序在某个特定时刻执行
    js设计模式-建造者模式
    css自定义字体完美解决方案example
    css透明属性
    css3多列example
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13355327.html
Copyright © 2020-2023  润新知