[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
相关文章
- [Angular] Introduce to NGXS
- [React Intl] Format Numbers with Separators and Currency Symbols using react-intl FormattedNumber
- [React] Create a Virtualized List with Auto Sizing Cells using react-virtualized and CellMeasurer
- [Angular] USING ZONES IN ANGULAR FOR BETTER PERFORMANCE
- [React Testing] Mock react-transition-group in React Component Tests with jest.mock
- [Angular] HttpParams
- [React] Create a Virtualized List with Auto Sizing Cells using react-virtualized and CellMeasurer
- [React] Create an Auto Resizing Virtualized List with react-virtualized
- [AngularJS] angular-md-table for Angular material design
- ES6, Angular,React和ABAP中的String Template(字符串模板)
- React的source code init时会自动检测Chrome dev tool的react extension装了没
- 利用 Angular Directive 和 @HostBinding 实现输入文本框随着键盘输入自动变色效果
- Angular 项目里 angular.json 文件内容的学习笔记
- Angular应用里setTimeout被如何被monkey patched的
- Angular formControl指令定义的位置
- Angular 页面元素的DOM级别的删除过程
- React(二)react脚手架的搭建