react useAuth高阶函数范型定义
原创
©著作权归作者所有:来自51CTO博客作者JediHongbin的原创作品,请联系作者获取转载授权,否则将追究法律责任
常见的需求 实现在点击一个按钮时判断用户是否登陆 如果没登陆跳转登陆页面 登录了则正常执行函数处理
tsx
<Button onClick={sendMessage}>发送</Button>
const { verifyAuth } = useAuth();
const sendMessage = verifyAuth(() => {
console.log(text.current);
});
useAuth
interface IContext {
verifyAuth: <T extends (...args: any) => any>(callback: T) => () => T;
}
/**
* 验证是否有用户登陆 没有则打开登陆页面
*/
const verifyAuth: IContext["verifyAuth"] = callback => {
if (!auth._id) {
return userProfileRef.current!.open;
}
return callback;
};
userProfileRef.current!.open();
export const userProfileRef = createRef<{ open: () => void }>();
const UserProfile: FC<IProps> = (): ReactElement => {
const mask = useRef<HTMLDivElement>(null);
const open = useCallback(() => {
setShow(true);
}, []);
useImperativeHandle(userProfileRef, () => ({ open }), [open]);
return (
<Mask ref={mask} show={show}>
// 登陆组件内容
</Mask>
);
};
const Mask = styled.div<{ show: boolean }>`
display: ${props => (props.show ? 'flex' : 'none')};
`;