[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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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