首页 > 其他分享 >react hooks + ts 封装组件

react hooks + ts 封装组件

时间:2023-03-17 09:47:48浏览次数:36  
标签:React const hooks ts react 组件 close open

react hooks+ts组件封装

简介

在react使用ts封装组件,需要注意类型, 使用 forwardRef 方法包起来

子组件

import * as React from "react";
import "./style.scss";

interface IPopup {
  open(): void;
  close(): void;
}

const UsePopup = React.forwardRef((props, ref: React.ForwardedRef<IPopup>) => {
  const [state, setState] = React.useState<boolean>(true);
  const open = () => {
    setState(true);
  };

  const close = () => {
    setState(false);
  };

  React.useImperativeHandle(ref, () => {
    return {
      open,
      close
    };
  });

  return (
    <div className="popup-container">
      {state ? (
        <div className="popup-wrapper">
          <div className="popup-mask" onClick={close}></div>
          <div className="popup-main">弹窗内容</div>
        </div>
      ) : null}
    </div>
  );
});

export default UsePopup;

父组件

interface IPopup {
  open(): void;
  close(): void;
}
const popupRef = React.useRef<IPopup>(null); // 使用useRef钩子

// 调用子组件方法
const popupClick = () => {
    popupRef.current?.open()
}

// 引用子组件
<UsePopup ref={popupRef}></UsePopup>

标签:React,const,hooks,ts,react,组件,close,open
From: https://www.cnblogs.com/sjie/p/17225461.html

相关文章