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

感谢你读到这里。

这座小站更像一份持续维护的“终端笔记”:记录我解决问题的过程,也记录走过的弯路。

如果这篇内容对你有一点点帮助:

  • 点个赞 / 收藏一下,方便你下次回来继续翻
  • 欢迎在评论区补充你的做法(或者指出我的疏漏)
  • 想持续收到更新:可以订阅 RSS(在页面底部)

我们下篇见。


More Posts

评论

评论 (0)

请先登录后再发表评论

加载中...