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>