zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

AngularReact to directive
2023-09-14 08:59:11 时间

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