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

原文地址:https://www.cnblogs.com/Answer1215/p/13355327.html