# react-useImperativeHandle

2 min read
Table of Contents

主要作用

核心特点

注意事项

总结

使用useImperativeHandle

父组件


子组件

count:0
import React, { useImperativeHandle, useRef, useState } from 'react'

interface ChildRef {
  name: string
  count: number
  addCount: () => void
  subCount: () => void
}

const Child = ({ ref }: { ref: React.Ref<ChildRef> }) => {
  const [count, setCount] = useState(0)
  useImperativeHandle(ref, () => {
    return {
      name: 'Child',
      count,
      addCount: () => setCount(count + 1),
      subCount: () => setCount(count - 1),
    }
  })
  return (
    <div>
      <h3>子组件</h3>
      <div>count:{count}</div>
      <button
        className="p-4 w-40 cursor-pointer border border-[#242424] rounded-md"
        onClick={() => setCount(count + 1)}
      >
        +1
      </button>
      <button
        className="p-4 w-40 cursor-pointer border border-[#242424] rounded-md"
        onClick={() => setCount(count - 1)}
      >
        -1
      </button>
    </div>
  )
}

function App() {
  const childRef = useRef<ChildRef>(null)
  const getChildInfo = () => {
    console.log(childRef.current)
  }
  return (
    <div>
      <h3>父组件</h3>
      <button className="p-4 w-40 cursor-pointer border border-[#242424] rounded-md" onClick={getChildInfo}>
        获取子组件信息
      </button>
      <button
        className="p-4 w-40 cursor-pointer border border-[#242424] rounded-md"
        onClick={() => childRef.current?.addCount()}
      >
        操作子组件count+1
      </button>
      <button
        className="p-4 w-40 cursor-pointer border border-[#242424] rounded-md"
        onClick={() => childRef.current?.subCount()}
      >
        操作子组件count-1
      </button>
      <hr />
      <Child ref={childRef} />
    </div>
  )
}

export default App
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments