ImperativeHandle Hook

2020-05-24  本文已影响0人  percykuang

ImperativeHandle Hook

函数:useImperativeHandle()

import React, { useImperativeHandle, useRef } from 'react'

function Test(props, ref) {

  // 第一个参数为ref 第二个参数是个函数 第三个参数是依赖项数组
  // 如果使用了依赖项,则第一次调用后,会进行缓存,只有依赖项发生变化时才会重新调用函数
  useImperativeHandle(ref, () => {
    // 该函数第一次加载组件后调用
    // 返回值相当于 ref.current = { method(){} }
    return {
      method() {
        console.log('i am a Test Component')
      }
    }
  }, [])

  return <h1 ref={ref}>Test Component</h1>
}

const TestWrapper = React.forwardRef(Test)

const App = () => {

  const testRef = useRef()

  return (
    <div>
      <TestWrapper ref={testRef}/>
      <button onClick={() => testRef.current.method()}>点击调用Test组件的method方法</button>
    </div>
  )
}

export default App
上一篇下一篇

猜你喜欢

热点阅读