[React] useImperativeHandle + forwardRef
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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‘.
以上是关于[React] useImperativeHandle + forwardRef的主要内容,如果未能解决你的问题,请参考以下文章
import * as react from 'react' 与 import react from 'react' 有啥区别
“使用 JSX 时,React 必须在范围内”(react/react-in-jsx-scope 与 index.js 上的“window.React = React”)