react 【ref转发forwardRef】【useImperativeHandle】

前言

  ref转发的使用场景比较少见,但是我们在编写组件库的时候,可能会需要使用到他,react.forward只适用于函数式组件

举个列子

  定义了一个FancyButton组件

const FancyBotton = (props: any) => {
  return (
    <div>
      <button>{props.children}</button>;
    </div>
  );
};

  你需要在使用时暴露button的ref

const App = () => {
  const ref = useRef(null);
  return (
    <div>
      <FancyButton ref={ref}>button</FancyButton> //这样只能获取FancyButton的ref,而不能转发button的ref
    </div>
  );
};

  那么我们需要如何在<FancyButton ref={ref}>button</FancyButton> 使ref能够转发到我们指定的元素上呢?

//使用forwardRef
//使用forwardRef之后,它使用时<FancyButton ref={ref}>button</FancyButton>,将ref作为组件函数的第二个参数
const FancyButton = react.forwardRef((props: any, ref: any) => {
  return (
    <div>
      <button ref={ref}>{props.children}</button>;
    </div>
  );
});

hook

  useRef:Reatc.crateRef

  useImperativeHandle:自定义转发给父组件的ref的值

    useImperativeHanle必须要与ofrwardRef一起使用

const FancyButton = react.forwardRef((props: any, ref: any) => {
  useImperativeHandle(
  //ref ref
,
  //第二个参数函数返回的值,会作为<FancyButton ref={ref}>button</FancyButton>上ref的值,此时为{click:fn} () => { return { click() { console.log("click run"); }, }; }, [deps] ); return ( <div> <button ref={ref}>{props.children}</button>; </div> ); });

 

    

 

posted @ 2022-01-21 11:04  眼里有激光  阅读(305)  评论(0编辑  收藏  举报