首页 > 其他分享 >[React] useImperativeHandle, similar to Angular Directive `exportAs`

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

时间:2022-12-09 22:00:27浏览次数:70  
标签:Directive useImperativeHandle component focus fancy React input ref

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

标签:Directive,useImperativeHandle,component,focus,fancy,React,input,ref
From: https://www.cnblogs.com/Answer1215/p/16970110.html

相关文章