[React] useImperativeHandle, similar to Angular Directive `exportAs`

Imagine you make a super fancy input component as part of your design system. Imagine that a parent element (i.e. the component that renders the fancy input) that needs to call focus() on the fancy input because of a validation error.

This is what useImperativeHandle is for. It allows a child component to expose a method (I used focus as an example but could be anything). You pass in a ref from useRef to the child component, it uses that ref to pass back methods to the parent. If you make libraries or design systems, this is useful. Otherwise there are easier ways to do this.

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef

posted @   Zhentiw  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-12-09 [Web] Possible bug for Cache the network request
2020-12-09 [Javascript] Broadcaster + Operator + Listener pattern -- 25. Save Network Requests by Using a Cache
2020-12-09 [Java Spring] Aspect
2019-12-09 [Algorithm] 242. Valid Anagram
2019-12-09 [Algorithm] 155. Min Stack
2017-12-09 [Python] Format Strings in Python
2017-12-09 [Python] Execute a Python Script
点击右上角即可分享
微信分享提示